Given an input string, reverse the string word by word.For example,Given s = "the sky is blue",return "blue is sky the".click to show clarification.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的split函數,把字符串按空格分成一個個子字符串,存到一個String[] strs里面,這時再把strs里的字符串從大到小反轉連接,中間加上空格就好了。需要注意如果原來的字符串有multiple spaces, 那會造成我們strs數組里面有一些子字符串是空字符串,我們反轉時若遇到這些空字符串,就要把它跳過。時間上split操作是O(N),再一次掃描獲得結果,也是O(N)。空間上使用了一個String[] 和StringBuffer,也是O(N)
本題就是需要注意一些語法,比如split函數的參數是String而不能是Char。我寫的時候不小心再一次犯了低級錯誤,String判斷是不是空字符串一定不要寫成if (str == ""), 要么用equals(), 要么用length()==0來判斷
注意 split()函數argument是一個string而不是char
1 public class Solution { 2 public String reverseWords(String s) { 3 if (s==null || s.length()==0) return s; 4 s.trim(); 5 String[] strs = s.split(" "); 6 StringBuffer res = new StringBuffer(); 7 for (int i=strs.length-1; i>=0; i--) { 8 if (strs[i].length() == 0) continue; 9 res.append(strs[i]);10 res.append(' ');11 }12 return res.toString().trim();13 }14 }
新聞熱點
疑難解答