Problem
Given a string 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.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
Solution
bool isValid(char * s){
if(*s == 0) return true;
int len = strlen(s),top = -1;
char stack[len]; //引入堆栈
for(int i=0; i<len; i++)
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
stack[++top] = s[i];//左括号们存入堆栈
else if(top == -1) return false;//无右括号
else if(s[i] == stack[top]+1 || s[i] == stack[top]+2)
top--;//右括号可以匹配
else return false;//右括号无法匹配
}
return top == -1;
}