[LeetCode] 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.
Solution:
class Solution { public: void reverseWords(string &s) { int len = s.length(), start = 0, curLen = 0; string ans = "", tmp = ""; bool isWord = false, notStartEmpty = false; for(int i = len - 1;i >= 0;i--) { if(s[i] == ' ') { if(isWord) { isWord = false; ans += s.substr(start - curLen + 1, curLen); curLen = 0; } if(notStartEmpty) tmp += s[i]; } else { if(isWord) { curLen++; } else { isWord = true; notStartEmpty = true; if(tmp.length() > 0) { ans += " "; tmp = ""; } start = i; curLen = 1; } } } if(curLen != 0) ans += s.substr(start - curLen + 1, curLen); s = ans; } };