Problem:
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.
Solution: Typical stack application, stack resolution, complexity O (n)
To give a string that contains only
‘(‘
,
‘)‘
,
‘{‘
,
‘}‘
,
‘[‘
and the
‘]‘
, the string that asks whether the decision is legal.
Java source code (spents 251ms):
public class Solution {public Boolean isValid (String s) { int length=s.length (), top=-1,index=0; Char[] Stack=new char[length]; Char[] Str=s.tochararray (); while (index<length) { if (str[index]== ') ') { if (top>=0 && stack[top]== ' (') top--; else return false; } else if (str[index]== '} ') { if (top>=0 && stack[top]== ' {') top--; else return false; } else if (str[index]== '] ') { if (top>=0 && stack[top]== ' [') top--; else return false; } else Stack[++top]=str[index]; index++; } return top==-1;} }
C Language Source code (1MS):
BOOL IsValid (char* s) { char stack[1000000]; int top=-1; while (*s) { if (*s== ') ') { if (top>=0 && stack[top]== ' (') top--; else return false; } else if (*s== '} ') { if (top>=0 && stack[top]== ' {') top--; else return false; } else if (*s== '] ') { if (top>=0 && stack[top]== ' [') top--; else return false; } else stack[++top]=*s; s++; } return top==-1;}
C + + source code (2ms):
Class Solution {public: bool IsValid (string s) { int top=-1,index=0,length=s.size (); char* stack= (char*) malloc (sizeof (char) *length); while (index<length) { if (s[index]== ') ') { if (top>=0 && stack[top]== ' (') top--; else return false; } else if (s[index]== '} ') { if (top>=0 && stack[top]== ' {') top--; else return false; } else if (s[index]== '] ') { if (top>=0 && stack[top]== ' [') top--; else return false; } else Stack[++top]=s[index]; index++; } return top==-1;} ;
python source code (42MS):
Class solution: # @param {string} s # @return {boolean} def isValid (self, s): Length=len (s); top=-1; Index=0 stack=["For I in range (length)" While index < length: if s[index]== ') ': if top>=0 and STA ck[top]== ' (': top-=1; Else:return False elif s[index]== '} ': if top>=0 and stack[top]== ' {': top-=1; Else:return False elif s[index]== ': if top>=0 and stack[top]== ' [': top-=1; Else:return False Else:top+=1;stack[top]=s[index] index+=1 return top==-1
Leetcode Valid parentheses (C,c++,java,python)