151. Reverse Words in a String
Leetcode StringGiven an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
Note:
A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
分析¶
这道题目如果用Python写的话很方便,如果要分割字符串,要用到String.split()
函数,但是这个函数只接受正则表达式!摔!气死!
用空格分割字符串的方法是String.split(\\s+)
,\s
表示空格。
public String reverseWords(String s) {
String[] list = s.trim().split("\\s+");
StringBuilder res = new StringBuilder();
for (int i = list.length - 1; i > 0; i--)
res.append(list[i]).append(" ");
res.append(list[0]);
return res.toString();
}