您的位置:首页 > 其它

【leetcode】20—valid parentheses

2015-04-28 12:51 417 查看




Valid Parentheses

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.

思路:一开始对题目要求理解有偏差,没有考虑 ([]) 这种情况,一直在想着用相邻两个字符ascii码相减来判断,后来看到tag里面有stack的提示,才想起来用栈。之后就很简单了。

class Solution {
public:
bool isValid(string s) {
stack<int>mys;
mys.push(s[0]);
for (int i=1;i<s.size();i++)
{
if (mys.empty())
{
mys.push(s[i]);
i++;
}
if(s[i]-mys.top()!=1&&s[i]-mys.top()!=2)
mys.push(s[i]);
else
mys.pop();
}
if (mys.empty())
{
return true;
}
else
return false;
}
};


测试时,出现的问题有:
1、测试例子为 ()[]时,第一对括号匹配成功并且都弹出后,栈为空,但是循环并未结束,因此再执行mys.top()时报错。出现这种情况后,加一个判断,如果栈为空,就push进当前的元素,并且i++。
2、注意栈的基本操作语句。主要是初始化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: