问题描述:
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;
}
};