Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
分析:细节实现题,基本思路为:将各单词从s中提取出来,存放在一个vector<string>中,然后清空s并逆序遍历vector<string>将单词和空格append到s中。代码如下:
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 int n = s.length(); 5 if(n == 0) return; 6 vector<string> res; 7 for(int i = 0; i < n;){ 8 while(i < n && s[i] == ' ')i++;//skip spaces 9 int j = i; 10 while(j < n && s[j] != ' ')j++; 11 if(i < n) res.push_back(s.substr(i,j-i)); 12 i = j; 13 } 14 s.clear(); 15 for(auto i = res.rbegin(); i != res.rend(); i++){ 16 s += *i + " "; 17 } 18 if(s.length() != 0) s.pop_back(); 19 } 20 };
浙公网安备 33010602011771号