Skip to content

Commit 901f0d8

Browse files
authored
Merge pull request #61 from purnasth/backspace/solution
feat: Backspace String Compare Problem JavaScript
2 parents f6b6fd4 + c91b92c commit 901f0d8

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Backspace String Compare</title>
7+
</head>
8+
<body>
9+
<button onclick="showCustomDialog()">Compare Strings</button>
10+
11+
<div id="custom-dialog" style="display: none">
12+
<p id="result-text">Result will be displayed here</p>
13+
</div>
14+
15+
<script>
16+
function showCustomDialog() {
17+
const customDialog = document.getElementById("custom-dialog");
18+
const resultText = document.getElementById("result-text");
19+
20+
const s = prompt("Enter the first string:");
21+
const t = prompt("Enter the second string:");
22+
const result = backspaceCompare(s, t);
23+
24+
customDialog.style.display = "block";
25+
26+
if (result) {
27+
resultText.innerHTML = `Are the first input "${s}" and the second input "${t}" equal after considering backspaces?<br><span style="color: green;">True</span>`;
28+
} else {
29+
resultText.innerHTML = `Are the first input "${s}" and the second input "${t}" equal after considering backspaces?<br><span style="color: red;">False</span>`;
30+
}
31+
}
32+
</script>
33+
<script src="./solution.js"></script>
34+
</body>
35+
</html>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Backspace String Compare Logic Starts Here
2+
const backspaceCompare = (s, t) => {
3+
const getNextValidCharIndex = (str, index) => {
4+
let backspaceCount = 0;
5+
while (index >= 0) {
6+
if (str[index] === "#") {
7+
backspaceCount++;
8+
index--;
9+
} else if (backspaceCount > 0) {
10+
backspaceCount--;
11+
index--;
12+
} else {
13+
break;
14+
}
15+
}
16+
return index;
17+
};
18+
19+
let sPointer = s.length - 1;
20+
let tPointer = t.length - 1;
21+
22+
while (sPointer >= 0 || tPointer >= 0) {
23+
sPointer = getNextValidCharIndex(s, sPointer);
24+
tPointer = getNextValidCharIndex(t, tPointer);
25+
26+
if (sPointer < 0 && tPointer < 0) {
27+
return true;
28+
}
29+
30+
if (sPointer < 0 || tPointer < 0 || s[sPointer] !== t[tPointer]) {
31+
return false;
32+
}
33+
34+
sPointer--;
35+
tPointer--;
36+
}
37+
38+
return true;
39+
};

0 commit comments

Comments
 (0)