LeetCode 20: Valid Parentheses
1264 ワード
Given a string containing just the characters
The brackets must close in the correct order,
タイトルは括弧が一致するかどうかを判断することを要求し,スタックによって実現できる.
コードは次のとおりです.
'('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid. The brackets must close in the correct order,
"()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not. タイトルは括弧が一致するかどうかを判断することを要求し,スタックによって実現できる.
コードは次のとおりです.
class Solution {
public:
bool isValid(string s) {
stack<char> opstack;
char c ;
for (int i=0; i<s.size(); i++)
{
c = s[i];
if ((c=='(') || (c=='[') || (c=='{'))
{
opstack.push(c);
}
else if ((c==')') || (c==']') || (c=='}'))
{
if (opstack.empty())
{
return false;
}
char tmp = opstack.top();
if ((c==')' && tmp=='(') || (tmp=='[' &&c==']' ) ||(tmp=='{' && c=='}'))
{
opstack.pop();
}else{
return false;
}
}
}
return opstack.empty();
}
};