[Leetcode] 20-valid parentheses

Source: Internet
Author: User

Original title Link: https://oj.leetcode.com/problems/valid-parentheses/


Checks if the sequence of parentheses is valid. The solution here is to maintain a stack, if it is an opening parenthesis, then push to the stack, if it is a closing parenthesis, then check the top of the stack symbol, if the corresponding parentheses, it will pop up. Otherwise, it returns false directly. When the string is scanned to the end, the stack is checked for null, and if it is empty, all parentheses are match.


Class Solution {Public:bool IsValid (string s) {stack<char> stk;        int i = 0;            while (I < s.size ()) {char c = s[i];                    Switch (c) {case ' (': Case ' [': Case ' {'): Stk.push (c);                    ++i;                Break                        Case ') ': if (!stk.empty () && stk.top () = = ' (') {stk.pop ();                        ++i;                    Break                    } else {return false; } case ': ' If (!stk.empty () && stk.top () = = ' [') {STK.P                        OP ();                        ++i;                    Break                    } else {return false;                     } Case '} ': if (!stk.empty () && stk.top () = = ' {') {   Stk.pop ();                        ++i;                    Break                    } else {return false;    }}} return Stk.empty (); }};


[Leetcode] 20-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.