This question has already been answered:

var str = prompt('Введите строку',''); function bracked(str) { var a = str.match(/\(/gm), b = str.match(/\)/gm); return a && b ? a.length == b.length : a == b; } alert(bracked(str)) 

The implementation of the task with brackets says that in the string)) ((they are arranged correctly

Reported as a duplicate by Darth , Grundy javascript Mar 15 '18 at 3:36 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Well, they are truly placed. In your task, the condition is that the number of opening brackets matches the number of closing brackets, so everything works fine. What is the question then? - Darth
  • Well, if you enter)) ((, then it will show correctly, I need in such cases that would give an error - Alexander Scherba
  • Why? What is the error then? What do you want from us? - Darth
  • It means that for each opening bracket there was its own closing one, and the opening one was before the closing one. Right? - Dan
  • The task was such: "Write a function that checks the correctness of the placement of the parentheses in the input string - takes the string and returns true or false depending on whether the brackets are arranged correctly in the string." As an example above, I sort of implemented. But if I type in the line closed. bracket, and then open. the bracket will show that everything is correct. how to do that would give an error in such variants. (the same cannot be closed, if they are not open) - Alexander Scherba

3 answers 3

 const str = prompt('Введите строку', '))(('); const bracked = str => 0 === [...str].reduce((opened, symbol) => { switch(true) { case opened === false: case opened < 0: return false; case symbol == '(': return ++opened; case symbol == ')': return --opened; default: return opened; } }, 0) console.log(str, bracked(str)) 

  • Beauty)) ..... - Dmitry Polyanin
  • Beauty? Well, I do not know, it is quite difficult to read this. - Zhukov Roman
  • @ZhukovRoman A teacher to explain - even more difficult, if not shary. All for young people) - Darth

Here is a validator that I wrote N years ago. The point is that we go in a row in a row, and if we meet an element from openers , then we add its index to the arr array. If we encounter an element from closers , then we compare its index with the last number in the arr array (removing it from this array) and if it is not equal to the index from closers , then validation is not passed.

This script can dump such nested sequences of different brackets: [()](){{}}

 var input = document.querySelector('input'); function isValid() { var str = input.value, openers = '<{[(', closers = '>}])', arr = [], valid = true; for (var i = 0, len = str.length; i < len; i++) { if (openers.indexOf(str[i]) >= 0) { arr.push(openers.indexOf(str[i])); } else if (closers.indexOf(str[i]) >= 0) { if (closers.indexOf(str[i]) != arr.pop()) { valid = false; } } } if (arr.length) { valid = false; } input.className = valid ? 'valid' : 'error'; } input.addEventListener('keyup', isValid) 
 * { font-size: 1.2em; } input { width: 98%; padding: 0.2em; } .error { background-color: #ffc6c6; } .valid { background-color: #bdffc6; } 
 <input type="text" /> 

  • one
    Why use indexes, each time calculating them, if the brackets themselves can be added to the stack? - Grundy
  • @Grundy try to do it according to your method, I did not consider such an algorithm. Every time calculating an index from what? From an array of 4-5 elements? This is a task for RosNano, I do not do such optimizations :) - Zhukov Roman

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:

  1. if the current character is an opening bracket, we put it on the stack
  2. if the current character is a closing bracket
    1. pushing a symbol from the top of the stack, if the received symbol is not an opening bracket - the string is not valid
    2. 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('([])[{()}]([])'))