-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0844-backspace-string-compare.js
More file actions
55 lines (49 loc) · 1.35 KB
/
0844-backspace-string-compare.js
File metadata and controls
55 lines (49 loc) · 1.35 KB
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
/**
* Backspace String Compare
* Time Complexity: O(lengthS + lengthT)
* Space Complexity: O(1)
*/
var backspaceCompare = function (stringOne, stringTwo) {
let currentPointerOne = stringOne.length - 1;
let currentPointerTwo = stringTwo.length - 1;
while (currentPointerOne >= 0 || currentPointerTwo >= 0) {
let backspaceCountOne = 0;
while (currentPointerOne >= 0) {
if (stringOne[currentPointerOne] === "#") {
backspaceCountOne++;
currentPointerOne--;
} else if (backspaceCountOne > 0) {
backspaceCountOne--;
currentPointerOne--;
} else {
break;
}
}
let backspaceCountTwo = 0;
while (currentPointerTwo >= 0) {
if (stringTwo[currentPointerTwo] === "#") {
backspaceCountTwo++;
currentPointerTwo--;
} else if (backspaceCountTwo > 0) {
backspaceCountTwo--;
currentPointerTwo--;
} else {
break;
}
}
const resolvedCharOne =
currentPointerOne >= 0 ? stringOne[currentPointerOne] : null;
const resolvedCharTwo =
currentPointerTwo >= 0 ? stringTwo[currentPointerTwo] : null;
if (resolvedCharOne !== resolvedCharTwo) {
return false;
}
if (currentPointerOne >= 0) {
currentPointerOne--;
}
if (currentPointerTwo >= 0) {
currentPointerTwo--;
}
}
return true;
};