問題描述:
給定一個字符串,你需要反轉字符串中每個單詞的字符順序,同時仍保留空格和單詞的初始順序。
示例 1:
輸入: "Let's take LeetCode contest" 輸出: "s'teL ekat edoCteeL tsetnoc"
注意:在字符串中,每個單詞由單個空格分隔,並且字符串中不會有任何額外的空格。
基本思路:
- 利用stringstream取出單詞。
- 利用反向迭代器獲得字符串逆序。
AC代碼:
class Solution {
public:
string reverseWords(string s) {
// 取出每一個單詞
string res;
stringstream sstream;
sstream << s;
bool first = true;
while (sstream) {
// 流也是先進先出的
string temp;
sstream >> temp;
if (temp == "") break; // 不知道爲什麼,好像最後還會輸出一個空字符串
string reverse(temp.rbegin(), temp.rend());
if (first) {
res += reverse;
first = false;
} else {
res += " ";
res += reverse;
}
}
return res;
}
};
其他經驗:
stringstream最後還會輸出一個空字符串,注意區別。