代码
/*
* @lc app=leetcode.cn id=20 lang=cpp
*
* [20] 有效的括号
*/
#include<stack>
#include<string>
using namespace std;
// @lc code=start
class Solution {
public:
bool isValid(string s) {
stack<char> sp;
int size = s.size();
for(int i=0; i<size; ++i)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
{
sp.push(s[i]);
}
else
{
if(sp.empty()==false)
{
char topc = sp.top();
switch(s[i])
{
case ')':
if(topc == '(')
{
sp.pop();
break;
}
else
{
return false;
}
case '}':
if(topc == '{')
{
sp.pop();
break;
}
else{
return false;
}
case ']':
if(topc == '[')
{
sp.pop();
break;
}
else{
return false;
}
default:
break;
}
}
else
{
return false;
}
}
}
if(sp.empty() == false)
{
return false;
}
return true;
}
};
// @lc code=end
结果
Accepted
96/96 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 42.07 % of cpp submissions (6.6 MB)