您的位置:首页 > 其它

leetcode-20-Valid Parentheses

2016-05-04 19:56 531 查看
题意:判断三种括号出现的次序是否正确。

比如:([{}]),{}[] ,()都为true。{[}]为false。

直接用栈。遍历一遍遇到左边的括号入栈,在栈不为空的情况下遇到第一个右边的括号时候判断栈顶元素是否对应。

class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=[]
map={")":"(","]":"[","}":"{"}
for i in s:
if i in "({[":
stack.append(i)
else:
if not stack or stack.pop()!=map[i]:
return False
return not stack


cpp:

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.empty())
return false;
if (stk.top() == '(' && s[i] == ')')
stk.pop();
else if (stk.top() == '[' && s[i] == ']')
stk.pop();
else if (stk.top() == '{' && s[i] == '}')
stk.pop();
else
return false;
}
}
return stk.empty();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: