Leetcode 20.Valid Parentheses (valid brackets) ideas and methods for solving problems

Source: Internet
Author: User

Valid parentheses
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.


Ideas: The overall topic is more clear, is the parentheses are effective to make judgments, the algorithm is implemented with a stack, one-sided into the stack, after pairing out the stack, the last to determine whether the stack is empty, not NULL description is not the last pairing completed, return false.

The specific code is as follows:

public class Solution {public Boolean isValid (String s) {stack<character> st = new Stack<character&gt        ;();        char[] ch = s.tochararray ();        int len = ch.length;        If the length is odd, it is definitely invalid if ((len & 1)! = 0) {return false;            } for (int i = 0; i < len; i++) {if (St.isempty ()) {//stack is empty, directly into stack St.push (ch[i]); }else{//is not empty, it discusses whether the top element of the stack is paired with Ch[i].                    Pairing is also out of the stack if (IsMatch (St.peek (), Ch[i]) {//Is paired st.pop ();//stack top element out of stack}else{    St.push (Ch[i]);//Unworthy to Stack}}} return St.isempty (); //A is the top element of the stack, B is the first element of the string public static Boolean IsMatch (char A, char b) {switch (a) {case ' (': if (b = = ') ) ') return true;            else return false; Case ' {': if (b = = '} ') return true;            else return false; Case ' [': if (b = = '] ') return true;            else return false;        Default:return false;   } }} 


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 20.Valid Parentheses (valid brackets) ideas and methods for solving problems

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.