Given an input string s
, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Example 4:
Input: s = " Bob Loves Alice " Output: "Alice Loves Bob"
思路:不用while (i < j),直接从最后一位开始倒贴就行了。这是一个好思路!
光是split就行了,不用再加toarray。
区别:toCharArray()是变成char array, split是变成string array
String[] words = s.split("\s+");
字符串连接:明明就只有+和concat(),StringBuildr sb才用append()
class Solution {
public String reverseWords(String s) {
//cc
if (s == null || s == "")
return "";
//分成words[]数组
//光是split就行了,不用再变成array
String[] words = s.split("\s+");
String result = "";
//倒贴
for(int i = words.length - 1; i > 0; i--) {
//字符串连接明明就只有+和concat(),StringBuildr sb才用append()
result += words[i];
result += " ";
}
result += words[0];
return result;
}
}