LeetCode 20 Valid Parentheses(用栈判断括号匹配)
2017-07-04 19:42
555 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
题目大意:给出一个包含三种括号的序列,判断括号是否匹配。
解题思路:用一个栈保存未匹配的左括号,然后遍历字符串,判断当前字符是左括号还是右括号。如果当前字符是左括号,那么将其入栈;如果当前字符是右括号且栈非空,那么判断是否与栈顶的左括号相匹配,如果匹配则弹出栈顶元素,不匹配则返回false。最后判断栈是否为空。
代码如下:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
int len = s.length();
for(int i = 0;i < len;i++){
if(s[i] == '{' || s[i] == '[' || s[i] == '(') {
stk.push(s[i]);
} else if(stk.size() && isPair(stk.top(), s[i])){
stk.pop();
} else {
return false;
}
}
return stk.empty();
}
private:
bool isPair(char x, char y) {
if( (x == '{' && y == '}') ||
(x == '[' && y == ']') ||
(x == '(' && y == ')') ){
return true;
}
else return false;
}
};
'(',
')',
'{',
'}',
'['and
']',
determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are
all valid but
"(]"and
"([)]"are
not.
题目大意:给出一个包含三种括号的序列,判断括号是否匹配。
解题思路:用一个栈保存未匹配的左括号,然后遍历字符串,判断当前字符是左括号还是右括号。如果当前字符是左括号,那么将其入栈;如果当前字符是右括号且栈非空,那么判断是否与栈顶的左括号相匹配,如果匹配则弹出栈顶元素,不匹配则返回false。最后判断栈是否为空。
代码如下:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
int len = s.length();
for(int i = 0;i < len;i++){
if(s[i] == '{' || s[i] == '[' || s[i] == '(') {
stk.push(s[i]);
} else if(stk.size() && isPair(stk.top(), s[i])){
stk.pop();
} else {
return false;
}
}
return stk.empty();
}
private:
bool isPair(char x, char y) {
if( (x == '{' && y == '}') ||
(x == '[' && y == ']') ||
(x == '(' && y == ')') ){
return true;
}
else return false;
}
};
相关文章推荐
- Leetcode 20 Valid Parentheses 判断括号匹配
- LeetCode20——Valid Parentheses(括号匹配问题,使用栈的知识)
- leetcode 20 Valid Parentheses 括号匹配
- LeetCode Valid Parentheses(判断括号是否匹配)
- leetcode 20 Valid Parentheses 括号匹配
- LeetCodet题解--20. 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-Longest Valid Parentheses-最长匹配括号-栈的应用
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- LeetCode 20 Valid Parentheses(有效的括号)
- LeetCode | Longest Valid Parentheses(最长有效的括号匹配)
- leetcode题解:Valid Parentheses(栈的应用-括号匹配)
- (leetcode)Valid Parentheses --- 括号匹配问题