Skip to content

Commit 1ae78da

Browse files
authored
Merge pull request chipbk10#105 from chipbk10/TwoPointers
Solve Problem 844 - Backspace String Compare
2 parents 7bec761 + 981ea33 commit 1ae78da

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package twopointers;
2+
3+
public class Problem844_BackspaceStringCompare {
4+
5+
private int down(String s, int i) {
6+
int count = 0;
7+
while (i >= 0 && (s.charAt(i) == '#' || count > 0)) {
8+
count = (s.charAt(i--) == '#') ? count+1 : count-1;
9+
}
10+
return i;
11+
}
12+
13+
public boolean backspaceCompare(String S, String T) {
14+
for (int i = S.length()-1, j = T.length()-1; i >= 0 || j >= 0; i--, j--) {
15+
i = down(S, i);
16+
char cs = (i >= 0) ? S.charAt(i) : '.';
17+
18+
j = down(T, j);
19+
char ct = (j >= 0) ? T.charAt(j) : '.';
20+
21+
if (cs != ct) return false;
22+
}
23+
return true;
24+
}
25+
}

0 commit comments

Comments
 (0)