您的位置:首页 > 其它

leetcode -- Valid Parentheses

2014-08-13 22:00 302 查看

不要因为走的太远而忘记我们为什么出发

[问题描述]

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.

[解题思路]

经典括号匹配问题,使用栈模拟即可

bool Solution::isValid(std::string s)
{
std::stack<char> tmp;
for (int i = 0; i < s.length(); i ++){
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
tmp.push(s[i]);
else if (s[i] == ')'){
if (tmp.size() > 0 && tmp.top() == '(')
tmp.pop();
else
return false;
}
else if (s[i] == ']'){
if (tmp.size() > 0 && tmp.top() == '[')
tmp.pop();
else
return false;
}
else if (s[i] == '}'){
if (tmp.size() > 0 && tmp.top() == '{')
tmp.pop();
else
return false;
}
}
return tmp.size() == 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: