151. Reverse Words in a String
by Botao Xiao
Question
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
Thinking:
- Method
public class Solution {
public String reverseWords(String s) {
String[] tokens = s.trim().split(" +");
Collections.reverse(Arrays.asList(tokens));
return String.join(" ", tokens);
}
}
二刷
- 想到通过split函数实现。
- 有很多corner case需要考虑,个人觉得有一些corner case存在的价值不大。
- 相比一刷通过正则和String的reverse,这次的方法快了很多。
public class Solution { public String reverseWords(String s) { if(s == null || s.length() == 0) return s; String[] arr = s.split(" "); int len = arr.length; if(len == 0) return ""; StringBuilder sb = new StringBuilder(); sb.append(arr[len - 1]); for(int i = len - 2; i >= 0; i--) if(arr[i].length() > 0) sb.append(" " + arr[i]); return sb.toString(); } }
Subscribe via RSS