"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