题目:
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.
程序:
class Solution {
public:
bool isValid(string s) {
int l = s.length();
stack<char> st;
for(int i=0;i<l;i++)
{
if(s[i] == '(')
st.push(')');
else if(s[i] == '[')
st.push(']');
else if(s[i] == '{')
st.push('}');
else if(st.empty())
return false;
else if(st.top() != s[i])
return false;
else
st.pop();
}
return st.empty();
}
};
点评:
采用栈