Problem
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.
Solution
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) return s;
String[] strs = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String str: strs) {
str = reverse(str);
sb.append(str).append(" ");
}
return sb.toString().trim();
}
private String reverse(String str) {
StringBuilder sb = new StringBuilder();
for (int i = str.length()-1; i >= 0; i--) {
sb.append(str.charAt(i));
}
return sb.toString();
}
}
StringBuilder for everything
class Solution {
public String reverseWords(String s) {
String[] strs = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String str: strs) {
str = new StringBuilder(str).reverse().toString();
sb.append(str+" ");
}
return sb.toString().trim();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。