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.
Note:
A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
方法1:
思路:
和151. Reverse Words in a String 一样。但是由于不考虑空格可以直接按照先大翻转再小翻转。
参考:grandyang https://www.cnblogs.com/grandyang/p/5186294.html
这里的loop写法非常值得借鉴
易错点
- loop很容易写坏
- 下面的写法就谜一样的错了
//["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
//["e","u","l","b"," ","s","i"," ","y","k","s"," ","e","h","t"]
// s e
//["b","l","u","e"," ","s","i"," ","y","k","s"," ","e","h","t"]
// s e
// s e
//["b","l","u","e"," ","i","s"," ","y","k","s"," ","e","h","t"]
// s e
// s e
//["b","l","u","e"," ","i","s"," ","s","k","y"," ","e","h","t"]
// s e
// s e
class Solution {
public:
void reverseWords(vector<char>& str) {
reverse(str.begin(), str.end());
for (int i = 0, j = 0; i < str.size(); i = j + 1){
for (j = i; j < str.size(); j ++){
if (str[j] == ' ') break;
}
reverse(str.begin() + i, str.begin() + j);
}
return;
}
};
class Solution {
public:
void reverseWords(vector<char>& str) {
reverse(str.begin(), str.end());
int start = 0, end = 0;
int n = str.size();
while (end < n && start < n){
while (str[end] != ' '){
end++;
}
//reverse(str.begin() + start, str.begin() + end);
start = end + 1;
end = start;
}
return;
}
};
class Solution {
public:
void reverseWords(vector<char>& str) {
reverse(str, 0, str.size() - 1);
int begin = -1, end = 0, n = str.size();
for (int end = 0; end < n; end++) {
if (begin == -1) {
if (str[end] != ' ') begin = end;
}
// 这里不能是else,因为可能begin == end
if (end == n - 1 || str[end + 1] == ' ') {
reverse(str, begin, end);
begin = -1;
}
}
return;
}
void reverse(vector<char>& str, int left, int right) {
while (left < right) {
swap(str[left++], str[right--]);
}
return;
}
};