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;
}
};
关于堆栈的用法