-
Easy
-
Given a string
s
containing just the characters'('
,')'
,'{'
,'}'
,'['
and']'
, determine if the input string is valid.An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
class Solution:
def isValid(self, s: str) -> bool:
openb={"(":")","{":"}","[":"]"}
ans=[]
for i in s:
if i in openb:
ans.append(i)
else:
if ans==[]:
return False
check=ans.pop()
if openb[check]!=i:
return False
return ans == []
Notice that in the program we are using '' instead of "". In C they mean differently: Double quotes for strings and single quotes for characters.
bool isValid(char * s){
int n = strlen(s);
char* test=malloc(sizeof(char)*n);
char c,e;
int top=0;
for (int i=0;i<n;i++){
c=s[i];
if (c==')'){
if (top==0){
return false;
}
top-=1;
e=test[top];
if (e!='('){
return false;
}
}else if (c==']'){
if (top==0){
return false;
}
top-=1;
e=test[top];
if (e!='['){
return false;
}
}else if (c=='}'){
if (top==0){
return false;
}
top-=1;
e=test[top];
if (e!='{'){
return false;
}
}else{
test[top]=c;
top+=1;
}
}
return (top==0);
}