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.

解法1:

用两个指针指向需要reverse的部分,再分别reverse。把string转化成char array之后比较好操作。
char array到string可以用new string(a)来转化。
C++

1

Java

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
29
30
31
32
33
34
35
36
37
38
39
40
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return s;
}
int start = 0, end = 0;
char[] ch = s.toCharArray();
while (end < ch.length) {
if (ch[end] != ' ') {
end++;
} else {
// reverse substring from start to end
reverse(ch, start, end - 1);
while (end < ch.length && ch[end] == ' ') {
end++;
}
start = end;
}
}
reverse(ch, start, end - 1);
return new String(ch);
}
private void reverse(char[] ch, int start, int end) {
while (start < end) {
char temp = ch[start];
ch[start] = ch[end];
ch[end] = temp;
start++;
end--;
}
return;
}
}