Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
- Reduce them to a single space in the reversed string.
public String reverseWords(String s) {
// 先把字符掐头去尾,再用split方法按空格分开 再逆序输出字符数组 如果word中有多个空格
// 那在字符数组里也会把空格存进去 不过存的是个空东西 length为0 所以只要不把数组空字符输出就好了
s = s.trim();
String ss[] = s.split(" ");
String str = "";
for (int i=ss.length-1; i>=0; i--) {
if (ss[i].length() >= 1) {
str += ss[i] + " ";
}
}
return str.trim();
}