Skip to content

Instantly share code, notes, and snippets.

@thg303
Created April 28, 2019 07:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save thg303/b11a395159e607f032599a0e5c4645ce to your computer and use it in GitHub Desktop.
let input = '[{}]'
let input2 = '[[{}]()]'
let input3 = '[{})[]'
function isOk (inputString) {
let arr = inputString.split('');
let stack = []
for (let i = 0; i < arr.length; i++) {
if (['[', '{', '('].includes(arr[i])) {
stack.push(arr[i])
} else if ([')', ']', '}'].includes(arr[i])) {
let lastOne = stack.pop()
if (!lastOne) {
throw new Error('invalid syntax');
}
if (arr[i] === '}' && lastOne !== '{') {
throw new Error('invalid syntax');
}
if (arr[i] === ']' && lastOne !== '[') {
throw new Error('invalid syntax');
}
if (arr[i] === ')' && lastOne !== '(') {
throw new Error('invalid syntax');
}
// if lastOne was empty it's a
}
}
if (stack.length !== 0) {
throw new Error ('invalid syntax');
}
console.log(inputString, ' : OK')
}
try {
isOk(input3);
} catch (e) {
console.log(input3, ' : ERR:', e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment