给定一个字符串,反转输出
输入: “the sky is blue”
输出: “blue is sky the”
一开始直接使用字符数组检测空格组合输出 时间48毫秒
后来使用String[] l = s.trim().split(" ");截取空格分割字符串,直接用String相加 时间13毫秒
最后使用StringBuffer替换字符串相加 时间1毫秒
public String reverseWords(String s) {
String[] l = s.trim().split(" ");
StringBuffer sb = new StringBuffer();
for (int i = l.length - 1; i >= 0; i--) {
if (l[i].equals("")) continue;
sb.append(l[i]);
if (i > 0) sb.append(" ");
}
return sb.toString()
}