Created
February 10, 2025 17:41
-
-
Save tatsuyax25/86e9331e8a3561ced0a1fa5e6f0fe6cd to your computer and use it in GitHub Desktop.
You are given a string s. Your task is to remove all digits by doing this operation repeatedly: Delete the first digit and the closest non-digit character to its left.
Return the resulting string after removing all digits.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @return {string} | |
*/ | |
var clearDigits = function(s) { | |
while (true) { | |
let digitIndex = -1; | |
// Find the first digit in the string | |
for (let i = 0; i < s.length; i++) { | |
if (/\d/.test(s[i])) { // Check if the character is a digit | |
digitIndex = i; | |
break; | |
} | |
} | |
// If no digit found, exit the loop | |
if (digitIndex === -1) { | |
break; | |
} | |
let nonDigitIndex = -1; | |
// Find the closest non-digit character to the left of the digit | |
for (let i = digitIndex - 1; i >= 0; i--) { | |
if (/\D/.test(s[i])) { // Check if the character is not a digit | |
nonDigitIndex = i; | |
break; | |
} | |
} | |
// Remove both characters | |
if (nonDigitIndex !== -1) { | |
// Construct the new string without the non-digit character and the digit | |
s = s.slice(0, nonDigitIndex) + s.slice(nonDigitIndex + 1, digitIndex) + s.slice(digitIndex + 1); | |
} else { | |
// If there's no non-digit character to the left, just remove the digit | |
s = s.slice(0, digitIndex) + s.slice(digitIndex + 1); | |
} | |
} | |
return s; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment