Skip to content

Commit

Permalink
Merge pull request #61 from purnasth/backspace/solution
Browse files Browse the repository at this point in the history
feat: Backspace String Compare Problem JavaScript
  • Loading branch information
Chayandas07 authored Oct 26, 2023
2 parents f6b6fd4 + c91b92c commit 901f0d8
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Backspace_string_compare/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Backspace String Compare</title>
</head>
<body>
<button onclick="showCustomDialog()">Compare Strings</button>

<div id="custom-dialog" style="display: none">
<p id="result-text">Result will be displayed here</p>
</div>

<script>
function showCustomDialog() {
const customDialog = document.getElementById("custom-dialog");
const resultText = document.getElementById("result-text");

const s = prompt("Enter the first string:");
const t = prompt("Enter the second string:");
const result = backspaceCompare(s, t);

customDialog.style.display = "block";

if (result) {
resultText.innerHTML = `Are the first input "${s}" and the second input "${t}" equal after considering backspaces?<br><span style="color: green;">True</span>`;
} else {
resultText.innerHTML = `Are the first input "${s}" and the second input "${t}" equal after considering backspaces?<br><span style="color: red;">False</span>`;
}
}
</script>
<script src="./solution.js"></script>
</body>
</html>
39 changes: 39 additions & 0 deletions Backspace_string_compare/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Backspace String Compare Logic Starts Here
const backspaceCompare = (s, t) => {
const getNextValidCharIndex = (str, index) => {
let backspaceCount = 0;
while (index >= 0) {
if (str[index] === "#") {
backspaceCount++;
index--;
} else if (backspaceCount > 0) {
backspaceCount--;
index--;
} else {
break;
}
}
return index;
};

let sPointer = s.length - 1;
let tPointer = t.length - 1;

while (sPointer >= 0 || tPointer >= 0) {
sPointer = getNextValidCharIndex(s, sPointer);
tPointer = getNextValidCharIndex(t, tPointer);

if (sPointer < 0 && tPointer < 0) {
return true;
}

if (sPointer < 0 || tPointer < 0 || s[sPointer] !== t[tPointer]) {
return false;
}

sPointer--;
tPointer--;
}

return true;
};

0 comments on commit 901f0d8

Please sign in to comment.