括號配對問題,題目如下:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
例如`[{()}]`,`[]{}()`都是正確的配對,`{][}`,`)`都是錯誤的配對,空串也認爲是正確的配對。這是一個棧的問題,可以通過進棧出棧來進行匹配。 棧的特性就是先進後出,首先遍歷字符串,將左括號依次進棧直到遇到右括號,然後進行出棧與對比,若有一次不匹配則直接返回false,直到棧爲空或遇到左括號。然後繼續遍歷字符串和進棧操作,直到遍歷完成,最後返回true。
class Solution {
public:
bool isValid(string s) {
string left = "([{";
string right = ")]}";
stack<char> st;
for(int i=0;i!=s.size();++i)
{
if(right.find(s[i])!=right.npos)
return false;
while(left.find(s[i])!=left.npos)
{
st.push(s[i]);
++i;
}
while(!st.empty()&&left.find(s[i])==left.npos)
{
if(left.find(st.top())!=right.find(s[i]))
return false;
else
st.pop();
++i;
}
--i;
}
return true;
}
};
另一種比較巧妙的方法就是每遇到一個左括號,就將對應的右括號入棧,遇到右括號就與棧頂元素比較,若相等則出棧並繼續,若不相等則直接返回False。另外如果棧爲空時遇到右括號,也返回false。最後若棧爲空則匹配完成,返回true。
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i!=s.size();++i)
{
if(s[i]=='(')
st.push(')');
else if(s[i]=='[')
st.push(']');
else if(s[i]=='{')
st.push('}');
else if(st.empty()||st.top()!=s[i])
return false;
else
st.pop();
}
return st.empty();
}
};