将单词按空格分词,然后倒序拼接即可
代码:
1 void reverseWords(string &s) { 2 vector<string> words; 3 4 int start = -1; 5 int len = 0; 6 7 for (int i = 0; i < s.length(); i++) { 8 if (s[i] == ' ') { 9 if (len > 0) 10 words.push_back(s.substr(start, len)); 11 len = 0; 12 } 13 else { 14 if (len == 0) { 15 start = i; 16 len = 1; 17 } 18 else 19 len++; 20 } 21 } 22 if (len > 0) 23 words.push_back(s.substr(start, len)); 24 25 string res; 26 if (words.size() > 0) { 27 for (int i = words.size() - 1; i > 0; i--) 28 res += words[i] + " "; 29 res += words[0]; 30 } 31 32 s = res; 33 }
如果不使用额外的辅助空间,可以用递归,将原问题转化成颠倒第一个单词和剩下的单词,而剩下的单词是一个子问题,于是就这么做下去就可以了。代码待补充。原先做这道题的时候没有想到用这种方法,后来在面试Juniper的时候面试官问道了,当时我没想到,但是经过提示我才想到了这个方法,汗。