LeetCode 1 Reverse Words in a String
2014-08-15 21:52
316 查看
Given an input string, reverse the string word by word.
For example:
Given s = "the sky is blue",
return "blue is sky the".
原题链接
这道题没有什么技巧,主要是考察对字符串操作的掌握。
注意点:
1,对一个空字符串使用split(“ ”)会返回一个长度为1的空格字符串;
2,split(" ")对每一个空格都起作用,所以如果想把相连的空格当做一个处理,应该用split(" +"),即一个或多个空格;
3,用StringBuilder代替String来避免不必要空间的开辟。
For example:
Given s = "the sky is blue",
return "blue is sky the".
原题链接
这道题没有什么技巧,主要是考察对字符串操作的掌握。
注意点:
1,对一个空字符串使用split(“ ”)会返回一个长度为1的空格字符串;
2,split(" ")对每一个空格都起作用,所以如果想把相连的空格当做一个处理,应该用split(" +"),即一个或多个空格;
3,用StringBuilder代替String来避免不必要空间的开辟。
public class Solution { public String reverseWords(String s) { if(s==null) return null; String newStr = s.trim(); if(newStr.length()==0) return newStr; String[] words = newStr.split(" +"); StringBuilder sb = new StringBuilder(); for(int i=words.length-1; i>=0; i--){ sb.append(words[i]); if(i!=0){ sb.append(" "); } } return sb.toString(); } }
相关文章推荐
- 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