Skip to content

Commit 722fefc

Browse files
committed
add comment
1 parent 5a3da63 commit 722fefc

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

code/LeetCode/src/popular/ReverseWordsInAString.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,25 +25,32 @@ public String reverseWords(String s) {
2525
public String reverseWordsWithLessSpace(String s) {
2626
char[] chars = s.toCharArray();
2727
int len = chars.length;
28+
// step 1. reverse the whole string
2829
subReverse(chars, 0, len - 1);
30+
// step 2. reverse each word
2931
subReverseWords(chars, len);
30-
32+
// step 3. clean up spaces
3133
return subCleanBlankChar(chars, len);
3234
}
3335

36+
// trim leading, trailing and multiple spaces
3437
public String subCleanBlankChar(char[] chars, int len) {
3538
int i = 0, j = 0;
3639
char blankChar = ' ';
3740
while (j < len) {
41+
// skip spaces
3842
while (j < len && chars[j] == blankChar) {
3943
j++;
4044
}
45+
// keep non spaces
4146
while (j < len && chars[j] != blankChar) {
4247
chars[i++] = chars[j++];
4348
}
49+
// skip spaces
4450
while (j < len && chars[j] == blankChar) {
4551
j++;
4652
}
53+
// keep only one space
4754
if (j < len) {
4855
chars[i++] = blankChar;
4956
}
@@ -56,17 +63,21 @@ public void subReverseWords(char[] chars, int len) {
5663
char blankChar = ' ';
5764
int i = 0, j = 0;
5865
while (j < len) {
66+
// skip spaces
5967
while (j < len && chars[j] == blankChar) {
6068
j++;
6169
}
6270
i = j;
71+
// skip non spaces
6372
while (j < len && chars[j] != blankChar) {
6473
j++;
6574
}
75+
// reverse the word
6676
subReverse(chars, i, j - 1);
6777
}
6878
}
6979

80+
// reverse a[] from a[i] to a[j]
7081
public void subReverse(char[] chars, int startIndex, int endIndex) {
7182
while (startIndex < endIndex) {
7283
char temp = chars[startIndex];

0 commit comments

Comments
 (0)