Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

151. Reverse Words in a String #131

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

方法一运行时间长 public class Solution { public String reverseWords(String s) { String[] temp = s.trim().split("\s+"); String res = ""; //此处i >= 0要在最后return是调用trim()把最后一个空格删掉 //或者可以少循环一次,在最后加上最后一个元素temp[0] for(int i = temp.length-1; i >= 0; i--) { res = res + temp[i] + " "; } //res = res + temp[0]; return res.trim(); } } 方法二运行时间短 public String reverseWords(String s) { if(s == null || s.length() ==0) return s;

    String[] words = s.trim().split(" ");
    StringBuilder sb = new StringBuilder(s.length());
    for( int i=words.length-1; i>0; i--) {
        //NOTE: String.split(" ") will generate some "" when there are duplicate " ".
        //For this case, we should use equals() method rather than "=="
        if( words[i].equals("")) continue;
        sb.append(words[i].trim());
        sb.append(" ");
    }
    sb.append(words[0]);
    return sb.toString();
}
Shawngbk commented 7 years ago

image