in the case of one type of brackets, the problem can be solved simply by counting: with the opening bracket, increment the counter, and with the closing bracket reduce.
If the counter becomes negative, the string is incorrect, if after the completion of the check the counter is greater than 0, the string is incorrect.
var str = '))(('; function bracked(str) { var counter = 0; for (var i = 0; i < str.length; i++) { if (str[i] == '(') counter += 1; else { counter -= 1 if (counter < 0) return false; } } return counter == 0; } console.log(bracked('))(('), bracked('()(())()'))
This task can also be solved using the stack:
- if the current character is an opening bracket, we put it on the stack
- if the current character is a closing bracket
- pushing a symbol from the top of the stack, if the received symbol is not an opening bracket - the string is not valid
- if the opening go to the next character from the string
var str = '))(('; function bracked(str) { var stack = []; for (var i = 0; i < str.length; i++) { if (str[i] == '(') stack.push('('); else { var prev = stack.pop(); if (prev != '(') return false; } } return stack.length == 0; } console.log(bracked('))(('), bracked('()(())()'))
this approach quite simply expands to several types of brackets. To do this, you need to add an object to match the opening and closing characters, and instead of opening the stack to stack the closing.
var str = '))(('; function bracked(str) { var bracketmap = { '(':')', '{':'}', '[':']' }; var stack = []; for (var i = 0; i < str.length; i++) { if (str[i] in bracketmap) stack.push(bracketmap[str[i]]); else { var prev = stack.pop(); if (prev != str[i]) return false; } } return stack.length == 0; } console.log(bracked('([})]'), bracked('([])[{()}]([])'))