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.
String
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
原文:http://www.cnblogs.com/lingtingvfengsheng/p/4309610.html