Description:
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.
题意:将给定的字符串数组中的每个单词反序;
解法:我们可以先将给定的字符串数组按照空格分割,之后对每个单词进行反序;
Java
class Solution {
public String reverseWords(String s) {
String[] table = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String str : table) {
sb.append(reverse(str) + " ");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
private String reverse(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
}