-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackspaceStringCompare.java
57 lines (52 loc) · 1.02 KB
/
BackspaceStringCompare.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// https://leetcode.com/problems/backspace-string-compare/
// #two-pointer #stack
class Solution {
/*
summary
note
-
idea
- normalize()
- normalize S and T
*/
public boolean backspaceCompare(String S, String T) {
int i = S.length() - 1;
int j = T.length() - 1;
int backspaceS = 0;
int backspaceT = 0;
while (i >= 0 || j >= 0) {
// normalize
while (i >= 0) {
if (S.charAt(i) == '#') {
backspaceS++;
} else if (backspaceS > 0) {
backspaceS--;
} else {
break;
}
i--;
}
// normalize
while (j >= 0) {
if (T.charAt(j) == '#') {
backspaceT++;
} else if (backspaceT > 0) {
backspaceT--;
} else {
break;
}
j--;
}
// check
if (i >= 0 && j >= 0 && S.charAt(i) != T.charAt(j)) {
return false;
}
if ((i >= 0) != (j >= 0)) {
return false;
}
i--;
j--;
}
return true;
}
}