20. Valid Parentheses
https://leetcode.com/problems/valid-parentheses/
给定一个只含括号的字符串,判断字符串是否匹配
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for(int i=0; i<s.size(); ++i)
{
switch(s[i])
{
case ')':
if(!stk.empty() && stk.top()=='(')
stk.pop();
else
return false;
break;
case ']':
if(!stk.empty() && stk.top()=='[')
stk.pop();
else
return false;
break;
case '}':
if(!stk.empty() && stk.top()=='{')
stk.pop();
else
return false;
break;
default:
stk.push(s[i]);
}
}
if(!stk.empty())
return false;
else
return true;
}
};
结果:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.
Memory Usage: 6.2 MB, less than 100.00% of C++ online submissions for Valid Parentheses.