乐趣区

557. Reverse Words in a String III

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.
难度: easy
题目:给定字符串,返转字符串中的单词,保留空格和单词顺序。
思路:遍历,返转
Runtime: 11 ms, faster than 50.54% of Java online submissions for Reverse Words in a String III.Memory Usage: 38.7 MB, less than 96.70% of Java online submissions for Reverse Words in a String III.
class Solution {
public String reverseWords(String s) {
s = ” ” + s + ” “;
StringBuilder result = new StringBuilder();
int begin = 0, end = 0;
for (int i = 1; i < s.length() – 1; i++) {
char c = s.charAt(i);
if (c != ‘ ‘ && s.charAt(i – 1) == ‘ ‘) {
begin = i;
result.append(s.substring(end + 1, begin));
}
if (c != ‘ ‘ && s.charAt(i + 1) == ‘ ‘) {
end = i;
for (int j = end; j >= begin; j–) {
result.append(s.charAt(j));
}
}
}

return result.toString();
}
}

退出移动版