151. 反转字符串中的单词
方法一
class Solution {
public:string reverseWords(string s) {istringstream instr(s);vector<string> words{};string word;while(instr>>word){words.push_back(word);}int length = words.size();string result = words[length-1];for(int i = length - 2 ; i >= 0; i--){result = result + " " + words[i];}return result;}
};
方法二
class Solution {
public:string reverseWords(string s) {int k = 0;while(s[k] == ' '){k++;}s.erase(s.begin(), s.begin() + k);k = s.size() - 1;while(s[k] == ' '){k--;}s.erase(s.begin() + k + 1, s.end());int i = 0, j = 0;while (i < s.size()) {if(s[i] != ' '){i++;}else{j = i;while(s[j] == ' '){j++;}if(j-i>1){s.erase(s.begin()+i+1,s.begin()+j);}i++;}}reverse(s.begin(), s.end());int tag = 0;for (i = 0; i < s.size(); ++i) {if (s[i] == ' ') {reverse(s.begin() + tag, s.begin() + i);tag = i + 1;}}reverse(s.begin() + tag, s.begin() + i);return s;}
};