[LintCode] 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".

Have you met this question in a real interview?
Yes
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.

LeetCode上的原题,请参见我之前的博客Reverse Words in a String

解法一:

class Solution {
public:
/**
* @param s : A string
* @return : A string
*/
string reverseWords(string s) {
int storeIndex = , n = s.size();
reverse(s.begin(), s.end());
for (int i = ; i < n; ++i) {
if (s[i] != ' ') {
if (storeIndex != ) s[storeIndex++] = ' ';
int j = i;
while (j < n && s[j] != ' ') s[storeIndex++] = s[j++];
reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
i = j;
}
}
return string(s.begin(), s.begin() + storeIndex);
}
};

解法二:

class Solution {
public:
/**
* @param s : A string
* @return : A string
*/
string reverseWords(string s) {
string res = "", t = "";
istringstream is(s);
while (getline(is, t, ' ')) {
if (t.empty()) continue;
res = (res.empty() ? t : (t + " " + res));
}
return res;
}
};

解法三:

class Solution {
public:
/**
* @param s : A string
* @return : A string
*/
string reverseWords(string s) {
istringstream is(s);
is >> s;
string t;
while (is >> t) {
s = t + " " + s;
}
return (s[] == ' ') ? "" : s;
}
};
上一篇:promise和Angular中的 $q, defer


下一篇:mysql插入数据后返回自增ID的方法,last_insert_id(),selectkey