Created
June 7, 2022 10:08
-
-
Save bartwttewaall/7125e7b49703b3c1199436cecbd0f5d4 to your computer and use it in GitHub Desktop.
validate matching characters in string
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
const pairs = { | |
'{': '}', | |
'(': ')', | |
'[': ']', | |
'<': '>', | |
} | |
function isValid(input: string) { | |
const chars = input.split(''); | |
let stack: string[] = [], last: string; | |
do { | |
last = chars.shift(); | |
if (stack.length > 0 && pairs[stack[stack.length-1]] === last) { | |
stack.pop(); | |
} else { | |
stack.push(last); | |
} | |
} while (chars.length); | |
return stack.join('').length === 0; | |
} | |
// tests | |
isValid('{[({}{}())]}'); // true | |
isValid('{[({}{}())][]]}'); // false | |
isValid('{[({)}{}())][]]}'); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment