給定字符串,按單詞反轉。單詞由非空格字符組成。需處理:首尾空格去除、多空格合併為一。例:"the sky is blue" → "blue is sky the"。
class Solution {
public:
void reverseWords(string &s) {
// 1. 整體反轉
reverse(s.begin(), s.end());
// 2. 逐詞反轉 + 3. 清理空格(合併雙指針)
int n = s.size(), write = 0;
for (int read = 0; read < n; ) {
// 跳過空格
while (read < n && s[read] == ' ') ++read;
if (read == n) break;
// 寫入單詞起始位置
if (write > 0) s[write++] = ' ';
int start = write;
// 複製單詞並反轉
while (read < n && s[read] != ' ') s[write++] = s[read++];
reverse(s.begin() + start, s.begin() + write);
}
s.resize(write); // 截斷多餘尾部
}
};
string reverseWords(string s) {
stringstream ss(s);
string word, res;
vector words;
while (ss >> word) words.push_back(word);
for (int i = words.size()-1; i >= 0; --i) {
res += words[i];
if (i) res += ' ';
}
return res;
}
| 輸入 | 輸出 |
|---|---|
| " hello world " | "world hello" |
| "a good example" | "example good a" |
| " " | "" |