思路:遇到空格就输出空格前的字符串,最后一个字符串单独输出
不用栈
#include <iostream> #include <cstring> using namespace std; int main() { char s[1005]; int n; cin >> n; getchar(); while (n--) { gets(s); int k = 0; int m = strlen(s); for (int i = 0; i < m; i++) { if (s[i] == ' ') { for (int j = i - 1; j >= k; j--) { cout << s[j]; } cout << " "; k = i + 1; } } for (int i = m - 1; i >= k; i--) { cout << s[i]; } cout << endl; } }
用栈
#include <iostream> #include <cstdio> #include <string> #include <algorithm> #include <stack> using namespace std; int main() { int n; cin>>n; getchar(); while(n--) { string s; getline(cin,s); int len; len = (int)s.size(); stack<char>st; for(int i=0;i<len;i++) { if(s[i]!=' ') { st.push(s[i]); } if(s[i]==' '||i==len-1) { while(!st.empty()) { printf("%c",st.top()); st.pop(); } if(s[i]==' ') { printf(" "); } } } printf(" "); } return 0; }