- Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
Clarification
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
解法1:
class Solution {
public:
/*
* @param s: A string
* @return: A string
*/
string reverseWords(string &s) {
vector<string> words;
string result;
int len = s.size();
int pos = -1;
for (int i = 1; i < len; ++i) {
if ((s[i] == ' ') && (s[i - 1] != ' ')) {
words.push_back(' ' + s.substr(pos + 1, i - pos - 1));
pos = i;
} else if ((s[i] == ' ') && (s[i - 1] == ' ')) {
pos = i;
}
}
words.push_back(' ' + s.substr(pos + 1, len - pos - 1));
//reverse(words.begin(), words.end());
int index = words.size() - 1; // find the last word
//remove the leading ' '
if (words[index][0] == ' ') words[index] = words[index].substr(1, words[index].size() - 1);
for (auto w : words)
result = w + result;
return result;
}
};
解法2: 二刷代码如下:
- 注意当result刚开始为空时不要加’ '。
- isalnum(char)可以判断某个字符是否为数字和字母。但这里只需要判断是否为非空格即可。
class Solution {
public:
/*
* @param s: A string
* @return: A string
*/
string reverseWords(string &s) {
int n = s.size();
if (n == 0) return "";
string result;
int beginPos = 0, endPos = n - 1;
//while(!isalnum(s[beginPos])) beginPos++;
while(s[beginPos] == ' ') beginPos++;
//while(!isalnum(s[endPos])) endPos--;
while(s[endPos] == ' ') endPos--;
s = s.substr(beginPos, endPos - beginPos + 1);
n = s.size();
beginPos = 0, endPos = 1;
while (endPos < n) {
while(s[endPos] != ' ' && endPos < n) endPos++;
if (result.size() == 0)
result = s.substr(beginPos, endPos - beginPos);
else
result = s.substr(beginPos, endPos - beginPos) + ' ' + result;
while(s[endPos] == ' ' && endPos < n) endPos++;
beginPos = endPos;
}
return result;
}
};
三刷:
class Solution {
public:
string reverseWords(string s) {
int startPos = 0, endPos = s.size() - 1;
while(s[startPos] == ' ') startPos++;
while(s[endPos] == ' ') endPos--;
string res;
s = s.substr(startPos, endPos - startPos + 1);
int n = s.size();
reverseString(s, 0, n - 1);
startPos = 0, endPos = 0;
while (endPos < n) {
while (endPos < n && s[endPos] != ' ') endPos++;
reverseString(s, startPos, endPos - 1);
res = res + s.substr(startPos, endPos - startPos) + ' ';
startPos = endPos + 1;
while (startPos < n && s[startPos] == ' ') startPos++;
endPos = startPos;
}
res = res.substr(0, res.size() - 1);
return res;
}
private:
void reverseString(string &s, int start, int end) {
while (start < end) {
swap(s[start], s[end]);
start++; end--;
}
}
};