方法一运行时间长
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();
}
方法一运行时间长 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;