-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
55 lines (50 loc) · 885 Bytes
/
solution1.js
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
/**
* https://leetcode-cn.com/problems/backspace-string-compare/
*
* 844. 比较含退格的字符串
*
* Easy
*
* 94.66%
* 98.53%
*/
const backspaceCompare = (S, T) => {
let sIndex = S.length - 1
let tIndex = T.length - 1
while (sIndex >= 0 || tIndex >= 0) {
const s = S[sIndex] || ''
const t = T[tIndex] || ''
if (s === '#') {
sIndex = countIndex(S, sIndex)
continue
}
if (t === '#') {
tIndex = countIndex(T, tIndex)
continue
}
if (s !== t) {
return false
}
sIndex--
tIndex--
}
if (sIndex !== tIndex) {
return false
}
return true
}
function countIndex (str, index) {
let count = 1
for (let i = index - 1; i >= 0; i--) {
const s = str[i]
if (s === '#') {
count++
continue
}
count--
if (count === 0) {
return i - 1
}
}
return -1
}