leetcode题解:Valid Parentheses(栈的应用-括号匹配)
2014-07-07 16:21
375 查看
题目:
Given a string containing just the characters
The brackets must close in the correct order,
说明:
1)括号可嵌套,如{[()]}
实现:
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.
说明:
1)括号可嵌套,如{[()]}
实现:
class Solution { public: bool isValid(string s) { if(s.empty()) return false;//空字符串,false int len=strlen(s.c_str()); if(len==1) return false;//只有一个字符,false char pre; stack<char> char_stack; for(int i=0;i<len;i++) { if(isPop(s[i])) //该出栈顶元素 { if(!char_stack.empty()) { pre=char_stack.top();//取栈顶元素、并出栈 char_stack.pop(); if(!isChar(pre,s[i]))//是否匹配 return false; } else return false; } else //入栈 { char_stack.push(s[i]); } } return char_stack.empty();//栈空true,否则false } private: bool isPop(char t) //判断是否是)} ]符号,是则出栈栈顶元素 { if(t==')'||t=='}'||t==']') return true; else return false; } bool isChar(char t1,char t2)//判断两字符t1,t2是否匹配 { switch (t1) { case '(': { if(t2==')') return true; else return false; break; } case '{': { if(t2=='}') return true; else return false; break; } case '[': { if(t2==']') return true; else return false; break; } default: return false; } } };
相关文章推荐
- LeetCode-Longest Valid Parentheses-最长匹配括号-栈的应用
- LeetCodet题解--20. Valid Parentheses(括号匹配问题)
- (leetcode)Valid Parentheses --- 括号匹配问题
- LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- Leetcode 20 Valid Parentheses 判断括号匹配
- LeetCode 20 Valid Parentheses (括号匹配问题)
- LeetCode - 32 - Longest Valid Parentheses(括号匹配)
- leetcode 20 Valid Parentheses 括号匹配
- LeetCode 32 Longest Valid Parentheses (栈,括号匹配)
- 20.Valid Parentheses 栈的应用:括号匹配
- leetcode 20 Valid Parentheses 括号匹配
- LeetCode 32 Longest Valid Parentheses 最大合法括号匹配长度计算 动态规划算法有待学习
- LeetCode | Valid Parentheses(括号匹配)
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- LeetCode 20 Valid Parentheses(括号匹配)
- LeetCode Valid Parentheses(判断括号是否匹配)
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- LeetCode 20 Valid Parentheses 括号匹配问题
- LeetCode: Longest Valid Parentheses (求最长有效匹配括号子串的长度)