JS brackets matching

Source: Internet
Author: User
The question of matching JS brackets is a question of matching brackets on codewars.

Question

To determine whether the brackets {}, [], and () in the string match, consider nesting.

Example:

validBraces("(){}[]")     // true validBraces("(}")         // false validBraces("[(])")       // false validBraces("([{}])")     // true

Solution

There are only two situations at the root of this problem. One is parallel, that is, no nesting, such as () [] {}; the other is nested, for example, {[()]}. The first case is relatively simple, and the second case is difficult. The solution to nested conditions is to first match the braces in the innermost part, that is, we often say that the elements are collapsed from the inner.

Method 1:

function validBraces(braces){  while(/\(\)|\[\]|\{\}/g.test(braces)){    braces = braces.replace(/\(\)|\[\]|\{\}/g,"")  }  return !braces.length;}

In this way, find the pairs of parentheses and replace them with null strings, that is, delete them. Finally, judge whether the string length is 0. Yes, it indicates a full match. Otherwise, the ratio matches.
In fact, this kind of solution is a typical example of "starting to collapse from the inside ". Let's take {[()]} as an example. Now, only the () in the innermost part is paired and adjacent. After replacing () with a null string, [] is paired and adjacent, and then replaced with an empty string. In this way, the query continues cyclically until paired and adjacent parentheses are no longer found.

Method 2:

Function validBraces (braces) {let leftBraReg =/[\ (\ {\ []/, // stack = [], bracket, rightBracket braces = braces. split ('') for (bracket of braces) {if (leftBraReg. test (bracket) {stack. push (bracket)} else {switch (bracket) {case ')': rightBracket = stack. pop () if (rightBracket! = '(') {Return false} break case ']': rightBracket = stack. pop () if (rightBracket! = '[') {Return false} break case '}': rightBracket = stack. pop () if (rightBracket! ==' {') {Return false} break }}return stack. length = 0? True: false}

This method saves the left half-side brackets (, [, {into the stack, when traversing to the right half-side brackets, the stack executes the out-of-stack operation, and then matches the left half-side brackets of the out-stack with the half-side brackets that are traversed to see if they match the other half-side brackets. If the traversal is complete, the length of the stack is determined. If the value is 0, the stack is matched. Otherwise, the ratio matches.
Let's take {[()]} as an example. When the first three items are {, [, (in the stack, when traversing, compare the '(' back-out stack and) at the top of the stack to see if it matches. The same is true for the following] And.

Conclusion

Now it is gradually discovered that the data structure and regular expression are very important (the solution here is used separately). Although it is rarely used at ordinary times, there is an application scenario, you will find that the data structure and regular expression are powerful.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.