1 题目
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.
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.
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(); }