Leetcode Valid parentheses Bracket matching problem

Source: Internet
Author: User

Topic:

Given A string containing just the characters‘(‘,‘)‘,‘{‘,‘}‘,‘[‘and‘]‘, determine if the input string is valid.

The brackets must close in the correct order,"()"and"()[]{}"is all valid but"(]"and"([)]"is not.

Translation:

Give a string to determine if the parentheses match successfully.


Ideas:

With a word Fu Yi, read to a character when judged, if the top of the stack and the current character is satisfied with the left and right brackets matching, then pop, otherwise press the stack.

If the last stack is empty, the match succeeds.


Code:

public static Boolean isValid (String s) {if (s.length () = = 0) return true; Stack<character> st = New Stack<character> (), St.push (S.charat (0)), for (int i = 1; i< s.length (); i++) {if (! St.empty () && IsMatch (St.peek (), S.charat (i))//non-empty and the top of the stack matches the current character, pops up St.pop (); else {St.push (S.charat (i));}} if (St.empty ()) return True;return false;    } Public  Static  boolean ismatch (char A,char b) {if ((a== ' (' &&b== ') ') | | (a== ' {' &&b== '} ') | | (a== ' [' &&b== ']) return true;else return false;}


Leetcode Valid parentheses Bracket matching problem

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.