Title Description
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.
Thinking of solving problems
The matching judgment is realized by the stack. For each character in the string s, C, if C is not a closing parenthesis, it is pressed into the stack stack.
If C is the right parenthesis, determine if the stack is empty, empty means that there is no left parenthesis, directly return not valid, non-empty to take out the top of the stack character pre to compare, if it is a match
, the character that pops up the top of the stack continues to take the next character in S; if it does not match, the description is not valid and is returned directly. Once we have traversed the string s, note
There is also a situation here, that is, there are still characters in the stack are not matched, that is, the stack is not empty at this time, the description s is not valid, because as long as valid, a
All can be matched so that the opening parenthesis pops up. This keeps the stack out and returns True when the string is traversed and the stack is empty, where the stack size is larger than the string
s half of the time, stating that the parentheses are not enough to return false directly.
The code is as follows
#include <iostream> #include <stack> #include <string>using namespace Std;bool isValid (string s); void Main () {string s= "({[]}";cout<< isValid (s);} BOOL IsValid (string s) {if (S.size () ==0) return false;stack<char> s_stack;int n=s.size (); for (int i=0;i<n; i++) {if (s[i]== ' (' | | | s[i]== ' {' | | | s[i]== ' [') S_stack.push (S[i]), if (s[i]== ') ') {if (S_stack.empty () | | | S_stack.top ()! = ' (') {return false;} else S_stack.pop ();} if (s[i]== '} ') {if (S_stack.empty () | | | S_stack.top ()! = ' {') {return false;} else S_stack.pop ();} if (s[i]== '] ') {if (S_stack.empty () | | | S_stack.top ()! = ' [') {return false;} else S_stack.pop ();} if (S_stack.size () >N/2) {return false;}} if (S_stack.empty ()) return true;}
Leetcode-valid parentheses