解释:
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.
判断输入的括号是否合法。
思路:
很自然地想到运用stack来做,就是维护一个栈,当遇到'('
, '{'
, '['
的时候进站,当遇到 ')'
, '}'
, ']'
的时候,判断栈顶元素是否与钙元素匹配,若不匹配则返回false。
class Solution {
public:
bool isValid(string s) {
bool result = true;
int n = s.length();
stack<char> st;
for(int i = 0; i < n ; i++){
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
st.push(s[i]);
else
{
if(st.empty())
return false;
if(isMatch(st.top() , s[i]))
st.pop();
else
{
result = false;
break;
}
}
}
if(!st.empty())
result = false;
return result;
}
bool isMatch(char s1, char s2){
if(s1 == '(' && s2 == ')' || s1 == '[' && s2 == ']' ||s1 == '{' && s2 == '}')
return true;
else
return false;
}
};