您的位置:首页 > 其它

[LeetCode]Valid Parentheses

2015-11-12 10:09 369 查看
题目描述:(链接)

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.

解题思路:

用一个stack实现

class Solution {
public:
bool isValid(string s) {
for (int i = 0; i < s.size(); ++i) {
switch (s[i]) {
case '(':
case '{':
case '[': {
cache.push(s[i]);
break;
}
case ')': {
if (!isSuitable('(')) {
return false;
}
break;
}
case '}': {
if (!isSuitable('{')) {
return false;
}
break;
}
case ']': {
if (!isSuitable('[')) {
return false;
}
break;
}
}
}

if (!cache.empty()) return false;

return true;
}
private:
stack<int> cache;
bool isSuitable(int character) {
if (cache.empty()) {
return false;
}

int ch = cache.top();
if (ch != character) {
return false;
}

cache.pop();

return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: