题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
#include <iostream> #include <string> using namespace std; //将不是字符的内容使用空格替换 void changeOther(string& s) { for (int i = 0; i < s.size(); i++) { if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z') ) continue; else s[i] = ' '; } } void mySwap(string& s, int start, int end) { for (; start < end; start++, end--) { swap(s[start], s[end]); } } int main() { string s; getline(cin, s); //先将不是字符的内容使用空格替换 changeOther(s); //将字符到过来 mySwap(s, 0, s.size() - 1); int fast = 0; int low = 0; while ( fast+1 <= s.size()) { if (s[fast + 1 ] == ' ' || fast == s.size()-1) { if ((s[fast] >= 'a' && s[fast] <= 'z') || (s[fast] >= 'A' && s[fast] <= 'Z') ) { mySwap(s, low, fast); low = fast + 2; } } fast++; } for (int i = 0; i < s.size(); i++) { cout << s[i]; } return 0; }