您的位置:首页 > 其它

【LeetCode】20. Valid Parentheses

2018-03-07 15:36 369 查看
Description: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.思路:用堆栈。1.括号总是成对出现的,遇到左括号进栈2.遇到右括号则与栈顶符号比较,匹配则栈顶出栈3.重复代码如下:class Solution {
public:
bool isValid(string s)
{
if(s.size()==1)
return false;
stack<char> st;
for (int i = 0; i<s.size(); i++)
{
if ((s[i] == '(') || (s[i] == '[') || (s[i] == '{'))
st.push(s[i]);
else
{
if(st.empty())
return false;

if (s[i] == ')' && !st.empty() && st.top() == '(')
st.pop();
else if (s[i] == ')' && st.top() != '(' )
return false;

if (s[i] == ']' && !st.empty() && st.top() == '[')
st.pop();
else if (s[i] == ']' && st.top() != '[')
return false;

if (s[i] == '}' && !st.empty() && st.top() == '{')
st.pop();
else if (s[i] == '}' && st.top() != '{')
return false;

}
}
if(st.empty())
return true;
else
return false;

}
};关于堆栈的用法
点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: