Skip to content

Commit e37ba6a

Browse files
committed
feat(two-points): ✨双指针解决844
1 parent 6b9ab85 commit e37ba6a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Two-Points/844/solution1.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* https://leetcode-cn.com/problems/backspace-string-compare/
3+
*
4+
* 844. 比较含退格的字符串
5+
*
6+
* Easy
7+
*
8+
* 94.66%
9+
* 98.53%
10+
*/
11+
const backspaceCompare = (S, T) => {
12+
let sIndex = S.length - 1
13+
let tIndex = T.length - 1
14+
15+
while (sIndex >= 0 || tIndex >= 0) {
16+
const s = S[sIndex] || ''
17+
const t = T[tIndex] || ''
18+
19+
if (s === '#') {
20+
sIndex = countIndex(S, sIndex)
21+
continue
22+
}
23+
if (t === '#') {
24+
tIndex = countIndex(T, tIndex)
25+
continue
26+
}
27+
28+
if (s !== t) {
29+
return false
30+
}
31+
sIndex--
32+
tIndex--
33+
}
34+
35+
if (sIndex !== tIndex) {
36+
return false
37+
}
38+
return true
39+
}
40+
41+
function countIndex (str, index) {
42+
let count = 1
43+
for (let i = index - 1; i >= 0; i--) {
44+
const s = str[i]
45+
if (s === '#') {
46+
count++
47+
continue
48+
}
49+
count--
50+
if (count === 0) {
51+
return i - 1
52+
}
53+
}
54+
return -1
55+
}

0 commit comments

Comments
 (0)