LeetCode 151. Reverse Words in a String
原题链接在这里:https://leetcode.com/problems/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
".
题解:
把原有string s按照空格分开存入strArr中, 再从strArr尾部开始一个一个加到StringBuikder中即可.
Note: 1.这里学习了几个新的API, string.split(" ")可以按照空格把原有string分开但若是有连续空格比如"a a"中间有两个空格,就会拆成[a, , a], 中间的空格会保留。但若是用string.splict("\\s+")也是按照空格分开,但是上面连续两个空格时就不会额外拆出一个空格。
2. 若是string开头有空格,如" a", string.splict("\\s+")拆出的array长度为2, 也会包含空的string, strArr 会像["","a"]. 所以要像Simplify Path在加到StringBuikder前判定strArr[i].length()是否为0.
3.最后会多加一个 空格 在sb中,所以最后要用sb.deleteCharAt(sb.length()-1)消掉最后一个空格.
Time Complexity: O(s.length()).
Space: O(strArr.length).
AC Java:
1 class Solution { 2 public String reverseWords(String s) { 3 if(s == null || s.length() == 0){ 4 return s; 5 } 6 7 String [] arr = s.trim().split("\\s+"); 8 StringBuilder sb = new StringBuilder(); 9 for(int i = arr.length-1; i>=0; i--){ 10 sb.append(arr[i] + " "); 11 } 12 13 sb.deleteCharAt(sb.length()-1); 14 return sb.toString(); 15 } 16 }
跟上Reverse Words in a String II, Reverse Words in a String III.