标签:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
1 public class Solution { 2 /** 3 * @param s : A string 4 * @return : A string 5 */ 6 public String reverseWords(String s) { 7 if (s == null || s.length() <= 1) return s; 8 9 int start = 0; 10 List<Character> list = new ArrayList<Character>(); 11 s = s.trim(); 12 13 for (int i = 0; i < s.length(); i++) { 14 if (!(s.charAt(i) == ‘ ‘ && list.get(list.size() - 1) == ‘ ‘)) { 15 list.add(s.charAt(i)); 16 } 17 } 18 19 for (int i = 0; i < list.size(); i++) { 20 if (list.get(i) == ‘ ‘) { 21 swap(list, start, i - 1); 22 start = i + 1; 23 } 24 } 25 26 swap(list, start, list.size() - 1); 27 swap(list, 0, list.size() - 1); 28 29 StringBuilder sb = new StringBuilder(); 30 for (int i = 0; i < list.size(); i++) { 31 sb.append(list.get(i)); 32 } 33 return sb.toString(); 34 } 35 36 public void swap(List<Character> list, int i, int j) { 37 while (i < j) { 38 char temp = list.get(i); 39 list.set(i, list.get(j)); 40 list.set(j, temp); 41 i++; 42 j--; 43 } 44 } 45 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5646446.html