【LeetCode】20. Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
题意:返回这些括号的使用是否正确:
思路:碰到前括号,存入栈,碰到后括号,当和前括号对应的时候,前括号出栈,否则返回错误,最后栈底元素为0的话,返回正确
1 bool isValid(char* s) { 2 int flag[200]={0}; 3 int i=0,j=0; 4 int c; 5 while(s[i]) 6 { 7 if('('==s[i]) c=-1; 8 else if(')'==s[i]) c=1; 9 else if('{'==s[i]) c=-2; 10 else if('}'==s[i]) c=2; 11 else if('['==s[i]) c=-4; 12 else if(']'==s[i]) c=4; 13 if((c<0&&0==j)||(flag[j-1]<0&&c<0)) //前括号,入栈 14 { 15 flag[j]=c; 16 j++; 17 } 18 else if(!(c+flag[j-1])) //对应的后括号,出栈 19 { 20 j--; 21 flag[j]=0; 22 } 23 else //其他,返回错误 24 return false; 25 i++; 26 } 27 if(!flag[0]) 28 return true; 29 else 30 return false; 31 32 }
Python :
1 class Solution(object): 2 def isValid(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 pre = {'(':-1,'[':-2,'{':-4} 8 aft = {')':1,']':2,'}':4} 9 stk = [] 10 for item in s: 11 if item in pre: 12 stk.append(item) 13 if item in aft: 14 if not len(stk): 15 return False 16 if pre[stk.pop()]+aft[item]: 17 return False 18 return False if len(stk) else True