/**
* @param {string} s
* @return {string}
Approach:
1) Create a result array
2) Iterate over the input string
3) Create a set to hold all of the numbers
4) When we hit a number inside of the set, remove the leftmost element
5) Return the result string
Time O(n^2) Worst Case to shift elements
Space O(n)
var clearDigits = function(s) {
const result = s.split('')
const numbers = new Set('1234567890'.split(''))
console.log('result', result)
for (let i = 1; i < result.length; i++) {
if (numbers.has(result[i])) {
// console.log('result[i]', result[i - 1], result[i], i)
result.splice(i - 1, 2)
i-=2
// result.splice(i, 1)
}
}
if (numbers.has(result[0])) {
result.shift()
}
console.log('result', result)
return result.join('')
};
2nd Approach:
- Given that we know we just want to skip numbers we can
1) Create a count variable
2) Iterate backwards
3) Create a result string
4) Count how many numbers we have
5) Then skip over the corresponding characters
Time & Space O(n)
**/
var clearDigits = function(s) {
let result = ''
let count = 0
const numbers = new Set('1234567890'.split(''))
for (let i = s.length - 1; i >= 0; i--) {
if (numbers.has(s[i])) {
count++
} else if (count > 0) {
count--
} else {
result = s[i] + result
}
}
return result
}