题目
题解
最先想到是自己去拆解,这里介绍一种新的方法,stringstream,同时,虽然可以通过对原来的空格进行erase操作来实现,但是频繁的改变这东西会导致stirng频繁重新分配内存,建议少用,看看下面的 拆解 的标准答案。
代码
拆解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: string reverseWords(string s) { ranges::reverse(s);
int n = s.length(); int idx = 0; for (int i = 0; i < s.length(); i++) { if(s[i] != ' ') { if(idx != 0) s[idx++] = ' ';
int end = i;
while(end < n && s[end] != ' ') s[idx++] = s[end++];
reverse(s.begin() + idx - (end - i),s.begin() + idx);
i = end; } }
s.erase(s.begin() + idx,s.end()); return s; } };
|
stringstream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: string reverseWords(string s) { stringstream ss(s); string word; vector<string> words;
while (ss >> word) { words.push_back(word); }
reverse(words.begin(), words.end());
string result; for (int i = 0; i < words.size(); ++i) { if (i > 0) { result += " "; } result += words[i]; }
return result; } };
|
同时提醒在C++对字符串采用stringstream的方式进行分解的话可以指定分隔符号。具体使用说明可以看下面的例子。
1 2 3 4 5 6 7 8 9 10 11 12
| std::vector<std::string> splitString(const std::string& str, char delimiter) { std::vector<std::string> result; std::stringstream ss(str); std::string token; while (std::getline(ss, token, delimiter)) { result.push_back(token); } return result; }
|