您的位置:首页 > 编程语言 > C语言/C++

LeetCode 20. Valid Parentheses

2017-04-03 22:35 369 查看

Description

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.

Analysis

典型的栈结构应用。

Code

class Solution {
public:
bool isValid(string s) {
stack<char> t;
for (char c : s){
if (c == '(' || c == '{' || c == '[')
t.push(c);
else
switch (c){
case ')':
if (!t.empty() && t.top() == '(')
t.pop();
else return false;
break;
case '}':
if (!t.empty() && t.top() == '{')
t.pop();
else return false;
break;
case ']':
if (!t.empty() && t.top() == '[')
t.pop();
else return false;
break;
default:
return false;
}
}
if (t.empty())
return true;
else return false;
}
};


Appendix

Link: https://leetcode.com/problems/valid-parentheses/

Run Time: 3ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string stack cpp leetcode