0%

Leetcode557-reverseWordsInAStringIII

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
2
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.

Solution

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
class Solution {
public String reverseWords(String s) {
if (s == null) return "";
if (s.length() < 2) return s;

int i = 0;
int j = 0;
int id = 0;
char[] seq = s.toCharArray();
while (id < s.length()){
if (seq[id] == ' '){
j = id -1;
while(i < j){
char tmp = seq[i];
seq[i] = seq[j];
seq[j] = tmp;
i ++;
j --;
}
i = id + 1;
}
id ++;
}
j = id -1;
while(i < j){
char tmp = seq[i];
seq[i] = seq[j];
seq[j] = tmp;
i ++;
j --;
}


String res = new String(seq);
return res;
}
}