Given 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.
如果我们使用Java的String的split函数来做的话就非常简单了,没有那么多的幺蛾子,简单明了,我们首先将原字符串调用trim()来去除冗余空格,然后调用split()来分隔,分隔符设为"\\s+",这其实是一个正则表达式,\\s表示空格字符,+表示可以有一个或多个空格字符,那么我们就可以把单词分隔开装入一个字符串数组中,然后我们从末尾开始,一个个把单词取出来加入结果res中,并且单词之间加上空格字符,注意我们把第一个单词留着不取,然后返回的时候再加上即可
public class ReverseWordsinaString {
public static String reverseWords(String s) {
String res = "";
String[] words = s.trim().split("\\s+"); // "\\s" is same as " "
// String[] words = s.trim().split(" +");
for (int i = words.length - 1; i > 0; i--) {
res += words[i] + " ";
}
return res + words[0];
}
public static void main(String[] args) {
String s = "the sky is blue";
String rs = reverseWords(s);
System.out.println(rs);
}
}