Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
题目描述如上:很容易被误导而使用了split方法,对于经常用java的人来说写这种算法题反而有很多坑点,因为有太多api可用了。下面这个方法能通过所有的测试,但是因为时间复杂度高而被否了。原因之一就应该是使用了split等方法而使时间复杂度大于n。
public static String reverseWords(String s) {
String[] Splresult = s.split(" ");
String result = "";
if (Splresult.length <= 2) {
int len = s.trim().length();
if (len == 0) {
return "";
} else if (len == 1) {
return s.trim();
}
}
int i = 0;
for (i = Splresult.length - 1; i > 0; i--) {
result += Splresult[i];
if (i + 1 < Splresult.length - 1) {
result += " ";
}
}
if (!Splresult[i].equals(" ")) {
result += Splresult[i];
}
return result;
}
下面这个只用了一个length()方法,而且我还用一个变量把结果进行了存储而防止多次运算。时间复杂度为O(n)。
public static String reverseWords(String s) {
String CurStr = "";
String result = "";
s += " ";
int i = 0;
int len = s.length();
while (i < len) {
if (s.charAt(i) != ' ') {
CurStr += s.charAt(i);
} else if (result.length() == 0) {
result = CurStr + result;
CurStr = "";
} else if (CurStr.length() != 0) {
CurStr += " ";
result = CurStr + result;
CurStr = "";
}
i++;
}
return result;
}