问题:
给定一个输入字符串,字符串字反向词。例如
s = "the sky is blue
",
返回 "blue is sky the
".
我的答案:
class Solution { public: void reverseWords(string &s) { if(s.size() <= 0) return; string pattern = " "; string::size_type pos; vector<string> result; s += pattern; string::size_type size = s.size(); for(int i = 0;i < size;i++){ pos = s.find(pattern, i); if(pos < size){ string word = s.substr(i, pos - i); if(word.find(pattern) == -1 && word != "") result.push_back(word); i = pos + pattern.size() - 1; } } s = ""; if(result.size() <= 0) return; for(int i = result.size() - 1; i >= 1 ; i--){ s += result[i]; s += " "; } s += result[0]; } };
leetcoder系列001:c++字符串反转,布布扣,bubuko.com
时间: 2024-10-12 12:13:59