JavaScript fun: a pair of Arc

Source: Internet
Author: User
Let's take a look at some examples. We can quickly understand what it is called "pairing ". Let's take a look at some examples. We can quickly understand what it is called "pairing ".


validParentheses( "()" ) // => returns true

A left arc and a right arc make up exactly one pair.

The following is a two-way response:


validParentheses( "(())" ) // => returns true

Let's look at another complex point, which is called N pair:


validParentheses( "(())((()())())" ) // => returns true

The following brackets cannot be called "paired". They can only be called "single-camera ":


validParentheses( "(" ) // => returns false

In this example, there are two pairs, but there are still two right arc tickets:


validParentheses( ")(()))" ) // => returns false

Now, after listening to my introduction, let's take a look at the task:

Compile a validParentheses function and accept a string composed of Arc. If the arc is "paired", true is returned; otherwise, false is returned.
All input strings are non-empty, and there are only two arc types: left and right.

Ideas:

Since it is "paired up", let's take a one-to-one offset.

First, prepare an empty stack. When the left arc is reached, the stack enters the stack. When the right arc is reached, a "Left arc" is spit out to offset the two.

When all characters are completed, the stack is determined. If the stack is empty, All parentheses are offset, that is, "in pairs ".

The Code is as follows:


Function validParentheses (parens) {var stack = []; for (var I = 0; I
 
  




The above is the JavaScript interesting question: the content of the arc in pairs. For more information, see the PHP Chinese website (www.php1.cn )!

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.