Valid parenthesis
Article Directory
topic
Includes only a given (
, )
, {
, }
, [
, ]
string, determines whether the string is valid.
A valid string must meet:
- The left bracket must be closed with the same type of right bracket.
- The left bracket must be closed in the correct order.
Note that an empty string can be considered a valid string.
Example 1:
输入: "()"
输出: true
Example 2:
输入: "()[]{}"
输出: true
Example 3:
输入: "(]"
输出: false
Example 4:
输入: "([)]"
输出: false
Example 5:
输入: "{[]}"
输出: true
Function prototype
C function prototype:
bool isValid(char * s){}
Boundary judgment
bool isValid(char * s){
if( s == NULL || *s == '\0' )
return true;
}
Algorithm design: stack
Ideas: If you have the left half of the brackets (such as
(
, ,[
){
on the stack, the right half of the face brackets (such as)
, ,]
)}
and the top of the stack elements can match (is a pair of parentheses), then the stack, repeated this Process ... In the end, the empty stack is valid parentheses. If there are still parentheses on the stack, it means that there is no perfect match.
bool isValid(char * s){
if( s == NULL || *s == '\0' ) // 题目说:空字符串可被认为是有效字符串。
return true;
int len = strlen(s);
if ( !len ) return true;
char stack[len];
int top = -1;
for (int i = 0; i < len; ++i) {
if (top > -1 && ((stack[top] == '(' && s[i] == ')') || (stack[top] == '[' && s[i] == ']') || (stack[top] == '{' && s[i] == '}'))) {
top--;
} else {
stack[++top] = s[i];
}
}
return top == -1 ? true:false;
}