leetcode 142: Reverse Words in a String
2014-06-20 05:15
267 查看
Reverse Words in a String
Total Accepted: 17523Total Submissions: 126756
Given an input string, reverse the string word by word.
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.
// " fadf the fdasf fdfaf " // "a" public class Solution { public String reverseWords(String s) { if(s==null || s.length() == 0 ) return s; StringBuilder res = new StringBuilder(); StringBuilder sb = new StringBuilder(); for(int i=0; i<s.length(); i++) { char c = s.charAt(i); if( c != ' ' ) { sb.append(c); } else if(sb.length()!=0 ) { res.insert(0, " "); res.insert(0, sb.toString() ); sb = new StringBuilder(); } } if(sb.length()!=0 ) { res.insert(0, " "); res.insert(0, sb); } return res.length()==0 ? "" : res.substring(0, res.length()-1); } }
相关文章推荐
- Leetcode 第151题 最新题解 Reverse Words in a String
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- LeetCode(151)Reverse Words in a String
- Leetcode: Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode with Python】 Reverse Words in a String
- [LeetCode]Reverse Words in a String
- leetcode Reverse Words in a String
- [leetcode]Reverse Words in a String
- Leetcode_Reverse-Words-in-a-String
- LeetCode | Reverse Words in a String
- Reverse Words in a String (LeetCode)
- [Leetcode Solution] Reverse Words in a String
- LeetCode151:Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [leetCode]Reverse Words in a String
- leetcode - Reverse Words in a String
- [LeetCode] Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 【LeetCode】Reverse Words in a String