Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created June 7, 2022 10:08
Show Gist options
  • Save bartwttewaall/7125e7b49703b3c1199436cecbd0f5d4 to your computer and use it in GitHub Desktop.
Save bartwttewaall/7125e7b49703b3c1199436cecbd0f5d4 to your computer and use it in GitHub Desktop.
validate matching characters in string
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