[LeetCode] Reverse Words in a String
2014-03-12 21:21
495 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
click to show clarification.
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:
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
click to show clarification.
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; } };
相关文章推荐
- LeetCode:Reverse Words in a String (Java)
- [leetcode]Reverse Words in a String
- LeetCode 1 Reverse Words in a String
- Reverse Words in a String leetcode
- LeetCode题解——Reverse Words in a String
- [LeetCode 151] Reverse Words in a String
- 【LeetCode】-Reverse Words in a String
- leetCode(34):Reverse Words in a String
- [leetcode, python] Reverse Words in a String 反转字符串
- LeetCode 151 Reverse Words in a String (字符串处理 推荐)
- Leetcode——557. Reverse Words in a String III
- LeetCode *** 151. Reverse Words in a String
- 【Leetcode】Reverse Words in a String JAVA
- [LeetCode]Reverse Words in a String-反转单词
- LeetCode---Reverse Words in a String
- [LeetCode186]Reverse Words in a String II
- leetcode151: Reverse Words in a String
- LeetCode-Reverse Words in a String II
- [LeetCode]Reverse Words in a String
- Leetcode 151 Reverse Words in a String