做题博客链接
https://blog.youkuaiyun.com/qq_43349112/article/details/108542248
题目链接
https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
描述
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
提示:
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
示例
输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
初始代码模板
class Solution {
public String reverseWords(String s) {
}
}
代码
class Solution {
public String reverseWords(String s) {
char[] chs = s.toCharArray();
int len = 0;
int end = 0;
while (end < chs.length) {
if (chs[end] != ' ') {
len++;
} else {
reverse(chs, end - len, end - 1);
len = 0;
}
if (end == chs.length - 1 && chs[end] != ' ') {
reverse(chs, end - len + 1, end);
}
end++;
}
return new String(chs);
}
private void reverse(char[] chs, int start, int end) {
while (start < end) {
char temp = chs[start];
chs[start] = chs[end];
chs[end] = temp;
start++;
end--;
}
}
}