@@ -25,25 +25,32 @@ public String reverseWords(String s) {
25
25
public String reverseWordsWithLessSpace (String s ) {
26
26
char [] chars = s .toCharArray ();
27
27
int len = chars .length ;
28
+ // step 1. reverse the whole string
28
29
subReverse (chars , 0 , len - 1 );
30
+ // step 2. reverse each word
29
31
subReverseWords (chars , len );
30
-
32
+ // step 3. clean up spaces
31
33
return subCleanBlankChar (chars , len );
32
34
}
33
35
36
+ // trim leading, trailing and multiple spaces
34
37
public String subCleanBlankChar (char [] chars , int len ) {
35
38
int i = 0 , j = 0 ;
36
39
char blankChar = ' ' ;
37
40
while (j < len ) {
41
+ // skip spaces
38
42
while (j < len && chars [j ] == blankChar ) {
39
43
j ++;
40
44
}
45
+ // keep non spaces
41
46
while (j < len && chars [j ] != blankChar ) {
42
47
chars [i ++] = chars [j ++];
43
48
}
49
+ // skip spaces
44
50
while (j < len && chars [j ] == blankChar ) {
45
51
j ++;
46
52
}
53
+ // keep only one space
47
54
if (j < len ) {
48
55
chars [i ++] = blankChar ;
49
56
}
@@ -56,17 +63,21 @@ public void subReverseWords(char[] chars, int len) {
56
63
char blankChar = ' ' ;
57
64
int i = 0 , j = 0 ;
58
65
while (j < len ) {
66
+ // skip spaces
59
67
while (j < len && chars [j ] == blankChar ) {
60
68
j ++;
61
69
}
62
70
i = j ;
71
+ // skip non spaces
63
72
while (j < len && chars [j ] != blankChar ) {
64
73
j ++;
65
74
}
75
+ // reverse the word
66
76
subReverse (chars , i , j - 1 );
67
77
}
68
78
}
69
79
80
+ // reverse a[] from a[i] to a[j]
70
81
public void subReverse (char [] chars , int startIndex , int endIndex ) {
71
82
while (startIndex < endIndex ) {
72
83
char temp = chars [startIndex ];
0 commit comments