[Leetcode]35. Valid parentheses Valid brackets

Source: Internet
Author: User

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

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

Solution: Very simple topic, use stack. Traversing the input string, if the current word identifier the left half of the parentheses, it is pressed into the stack, if the right side of the parentheses, if the stack is empty, then directly return false, if not empty, the top of the stack element, if the corresponding left half parenthesis, then continue the loop, and return false instead.

classSolution { Public:    BOOLIsValid (strings) {intSS =s.size (); if(ss%2!=0) return false; Stack<Char>par;  for(inti =0; I < SS; i++)        {            Switch(S[i]) { Case '(':             Case '[':             Case '{': Par.push (S[i]); Break;  Case ')':                if(Par.empty () | | par.top ()! ='(')return false;                Par.pop ();  Break;  Case ']':                if(Par.empty () | | par.top ()! ='[')return false;                Par.pop ();  Break;  Case '}':                if(Par.empty () | | par.top ()! ='{')return false;                Par.pop ();  Break; default:                return false; }        }        returnPar.empty (); }};

[Leetcode]35. Valid parentheses Valid brackets

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.