LeetCode 20 Valid Parentheses(括号匹配)
2017-03-28 11:54
501 查看
[LeetCode 20]
Description
Given a string containing just the characters
The brackets must close in the correct order,
bool isValid(char* s) {
int top=0;
int i=1;
int length = strlen(s);
char stack[length];
if(length == 0 | length == 1) return 0;
for(i=0;i<strlen(s);i++){
if(top == 0){
stack[0] = s[i];
top ++;
continue;
}
switch(stack[top - 1]){
case '(':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == ')') top--;
else return 0;
break;
case '[':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == ']') top--;
else return 0;
break;
case '{':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == '}') top--;
else return 0;
break;
}
}
if(!top) return 1;
else return 0;
}
Description
Given a string containing just the characters
'(',
')',
'{',
'}',
'['and
']', determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are all valid but
"(]"and
"([)]"are not.
bool isValid(char* s) {
int top=0;
int i=1;
int length = strlen(s);
char stack[length];
if(length == 0 | length == 1) return 0;
for(i=0;i<strlen(s);i++){
if(top == 0){
stack[0] = s[i];
top ++;
continue;
}
switch(stack[top - 1]){
case '(':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == ')') top--;
else return 0;
break;
case '[':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == ']') top--;
else return 0;
break;
case '{':
if( s[i] == '{' || s[i] == '[' || s[i] == '(' ){
stack[top]=s[i];
top ++;
}
else if(s[i] == '}') top--;
else return 0;
break;
}
}
if(!top) return 1;
else return 0;
}
相关文章推荐
- leetcode 20 Valid Parentheses 括号匹配
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- LeetCode 20 Valid Parentheses 括号匹配问题
- LeetCodet题解--20. Valid Parentheses(括号匹配问题)
- LeetCode20——Valid Parentheses(括号匹配问题,使用栈的知识)
- Leetcode 20 Valid Parentheses 判断括号匹配
- leetcode 20 Valid Parentheses 括号匹配
- leetcode 20 Valid Parentheses 括号匹配
- LeetCode 20 Valid Parentheses (括号匹配问题)
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- LeetCode 20 Valid Parentheses(有效的括号)
- 20. Valid Parentheses(括号匹配,用桟)
- LeetCode-Longest Valid Parentheses-最长匹配括号-栈的应用
- LeetCode 20. Valid Parentheses(括号校验)
- [LeetCode] 20. Valid Parentheses 合法括号
- 20.Valid Parentheses 栈的应用:括号匹配
- 【LeetCode】 括号匹配1 Valid Parentheses - Easy Google ++
- 【LeetCode】最长括号匹配Longest Valid Parentheses
- LeetCode-20 Valid Parentheses(判断括号是否规范)
- 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题