LeetCode 题解之Reverse Words in a String

时间:2024-08-09 09:37:50

1、题目描述

LeetCode 题解之Reverse Words in a String

2、问题分析

使用一个vector存储每个单词。

3、代码

 void reverseWords(string &s) {
vector<string> v;
for (string::iterator it = s.begin(); it != s.end(); ) {
if (*it == ' ') {
it++;
}
else {
auto itr = it + ; while (*itr != ' ' && itr != s.end()) {
itr++;
} string sub = s.substr(it - s.begin(), itr - it);
v.push_back(sub);
if (itr == s.end())
break;
it = itr + ;
}
} s.clear();
for (vector<string>::reverse_iterator rv = v.rbegin(); rv != v.rend(); rv++) {
if (rv + != v.rend()) {
s += *rv;
s += ' ';
} else {
s += *rv;
}
} }