1、題目描述
給定一個字符串,逐個翻轉字符串中的每個單詞。
說明:
- 無空格字符構成一個單詞。
- 輸入字符串可以在前面或者後面包含多餘的空格,但是反轉後的字符不能包括。
- 如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。
2、示例
輸入: "the sky is blue"
輸出: "blue is sky the"
3、題解
解法一:暴力
基本思想:暴力法
- s的第一個單詞前面填補一個空格,使得翻轉後第一個單詞與第二個單詞間存在空格
- 從後往前遍歷字符串s,遇到單詞,將空格+該單詞拼接到res,使得每個單詞間存在空格
解法二:用stringstream做
#include<iostream>
#include<algorithm>
#include<vector>
#include<sstream>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
//基本思想:暴力法
//s的第一個單詞前面填補一個空格,使得翻轉後第一個單詞與第二個單詞間存在空格
if (s[0] != ' ')
s.insert(0, 1, ' ');
string res;
int i = s.size() - 1, pos;
//從後往前遍歷字符串s
while (i >= 0)
{
//遇到單詞,將空格+該單詞拼接到res,使得每個單詞間存在空格
if (s[i] != ' ')
{
pos = i;
while (i >= 0 && s[i] != ' ')
i--;
res += s.substr(i, pos - i + 1);
}
i--;
}
//去掉多的一個空格
if (res[0] == ' ')
res.erase(0, 1);
return res;
}
};
class Solution1 {
public:
string reverseWords(string s) {
//基本思想:用stringstream做
istringstream words(s); //words保存s的一個拷貝
string res, word;
//從流words中讀取單詞
while (words >> word)
{
res = " " + word + res;
}
//去掉多的一個空格
if (res[0] == ' ')
res.erase(0, 1);
return res;
}
};
int main()
{
Solution1 solute;
string s = "the sky is blue";
cout << solute.reverseWords(s) << endl;
return 0;
}