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
注:超越了100%的人啊!
Runtime: 0 ms.Your runtime beats 100.00 % of c submissions.
bool isValid(char s[]) {
//定义一个栈
char sign[10000];
int top = 0;
int i = 0;
while(s[i] != '\0'){
if(s[i] == '(' || s[i] == '{' || s[i] == '[' )
sign[++top] = s[i];
else if(s[i] == ')' && sign[top] == '(' && top > 0)
top--;
else if(s[i] == '}' && sign[top] == '{' && top > 0)
top--;
else if(s[i] == ']' && sign[top] == '[' && top > 0)
top--;
else
return false;
i++;
}
if(top == 0)
return true;
else
return false;
}