[leetcode]20. Valid Parentheses
2016-12-29 16:30
351 查看
class Solution {
public:
bool isValid(string s) {
int length=s.length();
if(length==0) return true;
if(length%2 != 0) return false;
char flag[6]={'(',')','{','}','[',']'};
stack<char> a;
a.push(s[0]);
for(int i=1; i<length; i++)
{
if(a.empty())
a.push(s[i]);
else
{
char tmp = a.top();
if( ((tmp==flag[0])&&(s[i]==flag[1])) || ((tmp==flag[2])&&(s[i]==flag[3])) || ((tmp==flag[4])&&(s[i]==flag[5])) )
a.pop();
else
a.push(s[i]);
}
}
if(a.empty())
return true;
else
return false;
}
};
Given a string containing just the characters '(',')','{','}','[',']', determine if the input string is valid.
The brackets must close in the correct order,"()" and "()[]{}" are all valid but "(]" and "([)]" are not valid
最开始看到这个问题以为是规律给出来的,比如说是这样的:(){}[](),这样的理解是不对的,([])这样的结果也是对的
所以,用栈这种数据结构来处理这种问题是最方便的,代码如下
public:
bool isValid(string s) {
int length=s.length();
if(length==0) return true;
if(length%2 != 0) return false;
char flag[6]={'(',')','{','}','[',']'};
stack<char> a;
a.push(s[0]);
for(int i=1; i<length; i++)
{
if(a.empty())
a.push(s[i]);
else
{
char tmp = a.top();
if( ((tmp==flag[0])&&(s[i]==flag[1])) || ((tmp==flag[2])&&(s[i]==flag[3])) || ((tmp==flag[4])&&(s[i]==flag[5])) )
a.pop();
else
a.push(s[i]);
}
}
if(a.empty())
return true;
else
return false;
}
};
Given a string containing just the characters '(',')','{','}','[',']', determine if the input string is valid.
The brackets must close in the correct order,"()" and "()[]{}" are all valid but "(]" and "([)]" are not valid
最开始看到这个问题以为是规律给出来的,比如说是这样的:(){}[](),这样的理解是不对的,([])这样的结果也是对的
所以,用栈这种数据结构来处理这种问题是最方便的,代码如下
相关文章推荐
- leetcode_20_Valid Parentheses (easy)
- LeetCode-20. Valid Parentheses
- LeetCode 20 -- Valid Parentheses
- LeetCode20: Valid Parentheses
- leetcode 20. Valid Parentheses
- 20. Valid Parentheses-leetcode-java
- Leetcode 20. Valid Parentheses
- leetcode题解-20. Valid Parentheses
- Leetcode 20 Valid Parentheses 判断括号匹配
- [leetcode Q20] Valid Parentheses
- LeetCodet题解--20. Valid Parentheses(括号匹配问题)
- leetcode - 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
- [leetcode 20] Valid Parentheses