Java uses a stack to judge valid parentheses

Source: Internet
Author: User

If the definition of a pattern such as "{}[] ()" or "{[()]}" is valid, "[{]" or "(" mode is invalid, then we can use a stack or recursive descent method to implement.)

I'm going to do this once with a stack.

The idea of realization is.

When the start symbol is encountered (' [', ' {' or ' ('), we push it into the stack. When the end symbol is encountered, the element inside the pop will see if it matches, otherwise it returns false.

     Public BooleanIsValid (String s) {Char[] cs =S.tochararray (); if(cs.length% 2! = 0)            return false; Stack<Character> stack =NewStack<character>();  for(inti=0;i<cs.length;i++){            if(cs[i]== ' [' | | cs[i] = = ' (' | | cs[i] = = ' {') {Stack.push (cs[i]); }Else{                if(Stack.isempty ())return false; Switch(Stack.pop ()) { Case‘(‘:                    if(cs[i]!= ') ')return false;  Break;  Case‘[‘:                    if(cs[i]!= '])return false;  Break;  Case‘{‘:                    if(cs[i]!= '} ')return false;  Break; }            }        }        if(!stack.isempty ())return false; return true; }

Java uses a stack to judge valid parentheses

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.