Skip to content

Commit b95cc3f

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 844_Backspace_String_Compare.java
1 parent 2937af1 commit b95cc3f

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed
Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
11
class Solution {
22
public boolean backspaceCompare(String s, String t) {
3-
String sTrimmed = trimString(s);
4-
String tTrimmed = trimString(t);
3+
int i = s.length() - 1, j = t.length() - 1, sCounter = 0, tCounter = 0;
54

6-
return sTrimmed.equals(tTrimmed);
7-
}
5+
while (i >= 0 || j >= 0) {
6+
while (i >= 0 && (s.charAt(i) == '#' || sCounter > 0)) {
7+
if (s.charAt(i) == '#') ++sCounter;
8+
else --sCounter;
9+
--i;
10+
}
811

9-
private String trimString(String str) {
10-
StringBuilder sb = new StringBuilder();
11-
int hyphenCnt = 0;
12+
while (j >= 0 && (t.charAt(j) == '#' || tCounter > 0)) {
13+
if (t.charAt(j) == '#') ++tCounter;
14+
else --tCounter;
15+
--j;
16+
}
1217

13-
for (int i = str.length() - 1; i >= 0; i--) {
14-
if (str.charAt(i) == '#') {
15-
hyphenCnt++;
18+
if (i >= 0 && j >= 0 && s.charAt(i) == t.charAt(j)) {
19+
--i;
20+
--j;
1621
} else {
17-
if (hyphenCnt == 0) {
18-
sb.append(str.charAt(i));
19-
} else {
20-
hyphenCnt--;
21-
}
22+
break;
2223
}
2324
}
2425

25-
return sb.reverse().toString();
26+
return i < 0 && j < 0;
2627
}
2728
}

0 commit comments

Comments
 (0)