leetcode ReverseWordsInString
z
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class ReverseWordsInString {
/*
Given an input string, reverse the string word by word.
Example:

Input: "the sky is blue",
Output: "blue is sky the".
Note:

A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
*/
public static String reverseWords(String s) {
char[] line = s.toCharArray();
int n = line.length;
if (n==0) return null;

//1. reverse the whole string
reverse(line, 0, n-1);

//2. reverse everywords
reverseWord(line, n-1);
// return new String(line);
//3. cleanSpace

return cleanSpace(line, n-1);
}
public static String cleanSpace(char[] array, int n){
int i=0;
int j=0;
while(j<n) {
while (j <= n && array[j] == ' ') j++;
while (j <= n && array[j] != ' ') array[i++] = array[j++];
while (j <= n && array[j] == ' ') j++;
System.out.println(i);
System.out.println(j);
if (j<n){
array[i++]=' ';
}
}
return new String(array).substring(0, i)+';';
}
public static void reverseWord(char[] array, int n){
int i=0;
int j=0;
while(i<n){
while(i<n && array[i]==' ') i++;
while(j<i || (j<n && array[j]!=' ') ) j++;
System.out.println(i);
System.out.println(j);
if (j==n){
reverse(array, i, j);
i=j;
}
else{
reverse(array, i, j-1);
i=j;
}
}

}
public static void reverse(char[] array, int i, int j){
while(i<j){
char temp = array[j];
array[j] = array[i];
array[i] = temp;
i++;
j--;
}

}
public static void main(String[] args){
String s = " the sky is blue ";

System.out.println(reverseWords(s));
}
}