[Leetcode 20] Valid Parentheses

Samuel Liu
1 min readOct 5, 2021

--

Description:

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

C code solution:

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;
}

Explanation:

用一個stack來儲存所有的左括號,若遇到非左括號類型,則pop一個element來看目前這個符號是否為同型態的右括號。注意有些極端狀況。1. 當stack還沒放任何左括號時,但已經要看右邊括號。2. 長度為奇數。3.當掃完string後stack仍有資料。以上狀況皆為false。

--

--