[leetcode 151]Reverse Words in a String
2015-03-02 19:42
411 查看
1 题目
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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.
Hide Tags
String
2 思路
根据题目提醒的思路,1 什么是一个单词:一串没有空格的字符 2 考虑前面和后面的空格 3 考虑两个单词之间多个空格
首先区分单词 java有个函数spilt,解决问题1
干掉前面和后面的单词,java有个函数 trim,解决问题2
得到带有""的单词数组后,可以再遍历一遍,若是"",则不加入,解决问题3
最后从威到头组成一个新的字符串,输出即可。
3 代码
Given an input string, reverse the string word by word.
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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.
Hide Tags
String
2 思路
根据题目提醒的思路,1 什么是一个单词:一串没有空格的字符 2 考虑前面和后面的空格 3 考虑两个单词之间多个空格
首先区分单词 java有个函数spilt,解决问题1
干掉前面和后面的单词,java有个函数 trim,解决问题2
得到带有""的单词数组后,可以再遍历一遍,若是"",则不加入,解决问题3
最后从威到头组成一个新的字符串,输出即可。
3 代码
public String reverseWords(String s){ s = s.trim(); String[] words = s.split(" "); ArrayList<String> arrayList = new ArrayList<String>(); for (String string : words) { if (!string.isEmpty()) { arrayList.add(string); } } if (arrayList.isEmpty()) { return ""; } int len = arrayList.size(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len - 1; i++) {//少加一个,避免最后一个单词后面有空格 sb.append(arrayList.get(len - i - 1)); sb.append(" "); } sb.append(arrayList.get(0)); 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-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】
- LeetCode:151_Reverse Words in a String | 字符串中单词的逆反 | Medium
- leetcode[151]:Reverse Words in a String
- leetcode 151: Reverse Words in a String
- 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 [151]
- Reverse Words in a String - LeetCode 151
- Java for LeetCode 151 Reverse Words in a String
- LeetCode151:Reverse Words in a String
- [LeetCode 151] Reverse Words in a String
- Leetcode 151:Reverse Words in a String
- leetcode-151 Reverse Words in a String
- LeetCode(151) Reverse Words in a String
- leetcode 151 —— Reverse Words in a String
- [leetcode151] Reverse Words in a String