Skip to content

Commit 91d07c6

Browse files
authored
Added backspace string compare solution (#340)
1 parent 8c3a2b3 commit 91d07c6

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/* 844. Backspace String Compare - (https://leetcode.com/problems/backspace-string-compare/)
2+
3+
Given two strings s and t, return true if they are equal when both are typed into empty text editors.
4+
'#' means a backspace character.
5+
6+
Note that after backspacing an empty text, the text will continue empty.
7+
8+
* -------Two pointer approach-------
9+
*/
10+
11+
public class BackspaceStringCompare {
12+
public boolean backspaceCompare(String S, String T) {
13+
int i = S.length() - 1;
14+
int j = T.length() - 1;
15+
int countS = 0;
16+
int countT = 0;
17+
while (i >= 0 || j >= 0) {
18+
while (i >= 0 && (countS > 0 || S.charAt(i) == '#')) {
19+
if (S.charAt(i) == '#')
20+
countS++;
21+
else
22+
countS--;
23+
i--;
24+
}
25+
char left = i < 0 ? '@' : S.charAt(i);
26+
while (j >= 0 && (countT > 0 || T.charAt(j) == '#')) {
27+
if (T.charAt(j) == '#')
28+
countT++;
29+
else
30+
countT--;
31+
j--;
32+
}
33+
char right = j < 0 ? '@' : T.charAt(j);
34+
if (left != right)
35+
return false;
36+
i--;
37+
j--;
38+
}
39+
return true;
40+
}
41+
}

0 commit comments

Comments
 (0)