[Leetcode] 20.Valid parentheses

Source: Internet
Author: User

"title"

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.

"Analysis"

This is the application of the stack.

Note the situation:

(1) []) the number of parentheses is mismatched, the left bracket is less, the right parenthesis is many, so the stack should be judged if the stack is empty if (!brackets.empty ())

(2) ( the number of left and right brackets does not match, the opening parenthesis is many, the closing parenthesis is less, so you need to determine whether the stack is empty

"Code"
/********************************** Date: 2015-01-23* sjf0115* title: 20.Valid parentheses* Website: https://oj.leetcode.com/p roblems/valid-parentheses/* Result: ac* Source: leetcode* Blog: **********************************/#include <iostream>#        Include <stack>using namespace Std;class solution {Public:bool IsValid (string s) {bool result = false;        int len = S.length ();        if (len <= 1) {return result;        }//if stack<char> brackets;               for (int i = 0;i < Len;++i) {//' (' [' {' {'}] = ' (' = '} ' = ' (' | | s[i] = = ' [' | | s[i] = = ' {') {               Brackets.push (S[i]);            Continue                }//if//Otherwise out of the stack, compare if (!brackets.empty ()) {Char bracket = brackets.top ();                Brackets.pop ();                if (s[i] = = ') ' && bracket! = ' (') {return false;         }//if if (s[i] = = '] ' && bracket! = ' [') {           return false;                }//if if (s[i] = = '} ' && bracket! = ' {') {return false;            }//if}//if//number mismatch else{return false;        }}//for if (!brackets.empty ()) {return false;    }//if return true;    }};int Main () {solution solution;    string s = "((";    BOOL result = Solution.isvalid (s);    Output cout<<result<<endl; return 0;}



[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.