[Leetcode 20] Valid Parentheses

Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
Input: s = "([)]"
Output: false
Input: s = "{[]}"
Output: true
bool isValid(char * s){
char *p = s;
char stack[strlen(s)];
int stack_size = 0;
while(*p){
if(*p == '(' || *p == '[' || *p == '{'){
stack[stack_size] = *p;
stack_size++;
}
else{
if(stack_size == 0)
return false;
char c = stack[stack_size-1];
char d = *p;
if(c == '('){
stack_size--;
if(d != ')')
return false;
}else if(c == '['){
stack_size--;
if(d != ']')
return false;
}else if(c == '{'){
stack_size--;
if(d != '}')
return false;
}
}
p++;
}

return stack_size == 0;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store