您的位置:首页 > 其它

[Leetcode]_20 Valid Parentheses

2017-04-26 22:36 387 查看
/**
*  Index: 20
*  Title: Valid Parentheses
*  Author: ltree98
**/


括号配对,利用栈先进后出的特点。

当出现右半部分时,必须与之前最后出现的左半部分配对成功,否则GG。

注意几个样例:

"["
"]"
"]["
"[(])"
"[()]"


class Solution {
public:
bool isValid(string s) {
stack<char> container;

for(int i = 0; i < s.length(); i++) {
switch(s[i])    {
case '(':
case '{':
case '[':   container.push(s[i]);   break;
case ')':   {if(container.empty() || container.top()!='(') return false; else container.pop();} break;
case '}':   {if(container.empty() || container.top()!='{') return false; else container.pop();} break;
case ']':   {if(container.empty() || container.top()!='[') return false; else container.pop();} break;
default: ;
}
}

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