Reverse Words in a String
问题:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
思路:
这个题目很简单,主要注意两个个corner case:1、s前后有空白符 2、s 中间分隔符是一个或者多个空白字符 所以split.(" +")而不是split(" ")
我的代码:
public class Solution { public String reverseWords(String s) { if(s == null || s.length() == 0) return s; s = s.trim(); StringBuffer part = new StringBuffer(); String rst = ""; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == ' ') { String tmp = part.toString(); if(tmp == null || tmp.equals("")) continue; else { rst = " " + part.toString() + rst; part = new StringBuffer(); } } else { part.append(s.charAt(i)); } } rst = part.toString()+rst; return rst; } }
他人代码:
public class Solution { public String reverseWords(String s) { s = s.trim(); String[] words = s.split(" +"); StringBuilder str = new StringBuilder(); if (words.length != 0) { for (int i = words.length - 1; i > 0; i--) { str.append(words[i] + " "); } str.append(words[0]); } return str.toString(); } }