Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
首先把字符串按照“ ”分割,然后挨个反转,最后拼接起来。代码如下:public class Solution {
public String reverseWords(String s) {
String[] strs = s.split("\\s", -1);
StringBuilder sb = new StringBuilder();
StringBuilder res = new StringBuilder();
for (String str: strs) {
sb.replace(0, sb.length(), str);
res.append(sb.reverse()).append(" ");
}
return res.deleteCharAt(res.length() - 1).toString();
}
}