第一种方法:使用栈
public static String reverseWords(String s) {
s = s.trim();
if (s == null || s.length() == 0) {
return "";
}
String allStr = "";
//入栈操作
int n = s.length();
Stack stack = new Stack();
String str = "";
for (int i = 0; i < n; i++) {
if (s.charAt(i) != 32) {
str += String.valueOf(s.charAt(i));
}
if (s.charAt(i) == 32 && s.charAt(i + 1) != 32) {
stack.push(str);
str = "";
}
}
stack.push(str);
while (!stack.empty()) {
str = String.valueOf(stack.pop());
for (int i = 0; i < str.length(); i++) {
allStr += String.valueOf(str.charAt(i));
}
allStr += " ";
}
return allStr.trim();
}
很遗憾,执行效率比较慢。
第二种方法:正则
public String reverseWords(String s) {
if (s == null || s.length() == 0) return s;
StringBuilder sb = new StringBuilder();
String[] words = s.trim().split("\\s+");
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i] + " ");
}
return sb.toString().trim();
}