LeetCode557-反转字符串中的单词III

题目链接

英文链接:https://leetcode.com/problems/reverse-words-in-a-string-iii/

中文链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/

题目详述

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1:

1
2
输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"

注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

题目详解

这题比较简单,以空格分割出每一个的单词,对单词进行反转操作,最后组合成一个字符串返回即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class LeetCode_00557 {

public String reverseWords(String s) {
char[] cs = s.toCharArray();
int i = 0;
while (i < cs.length) {
int begin = i;
while (i < cs.length && cs[i] != ' ') {
++i;
}
reverse(cs, begin, i - 1);
++i;
}
return new String(cs);
}

private void swap(char[] cs, int i, int j) {
char tmp = cs[i];
cs[i] = cs[j];
cs[j] = tmp;
}

private void reverse(char[] cs, int i, int j) {
while (i < j) {
swap(cs, i++, j--);
}
}
}