[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
".
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 = 0, n = s.size(); reverse(s.begin(), s.end()); for (int i = 0; i < n; ++i) { if (s[i] != ' ') { if (storeIndex != 0) 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[0] == ' ') ? "" : s; } };