問題描述:
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue
" Output: "blue is sky the
"
Example 2:
Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
源碼:
問題意思大概就是翻轉句子,並且把多個空格變成一個
這題和劍指offer第二版的58題很像。詳情可以看劍指offer總綱。不過需要多餘考慮的是多個空格爲問題。
思路就是先整個翻轉,然後對每個單詞依次翻轉,中間多考慮一下多空格問題。比如
I LOVE YOU->UOY EVOL I->YOU LOVE I
源碼如下:
class Solution {
public:
string reverseWords(string s) {
int n = s.length(), index = 0;
reverse(s.begin(), s.end());
for(int i=0; i<n; i++){
if(s[i] != ' '){
if(index != 0) s[index++] = ' ';
int j=i;
while(j<n && s[j]!=' ') s[index++] = s[j++];
reverse(s.begin()+index-(j-i), s.begin()+index);
i = j;
}
}
s.resize(index);
return s;
}
};
在網上查了一下,有大佬用字符流的方法做的,很巧妙:
第一種:
class Solution {
public:
string reverseWords(string s) {
istringstream is(s);
string tmp;
is >> s;
while(is >> tmp) s = tmp + " " + s;
if(!s.empty() && s[0] == ' ') s = "";
return s;
}
};
第二種:
class Solution {
public:
string reverseWords(string s) {
istringstream is(s);
s = "";
string t = "";
while (getline(is, t, ' ')) {
if (t.empty()) continue;
s = (s.empty() ? t : (t + " " + s));
}
return s;
}
};