解題思路
這題是 stack 很經典的題目──括號匹配問題。
記得想好 edgecase。
程式碼
class Solution {
public:
bool isValid(string s) {
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() && s[i] == ')' && st.top() == '(')
st.pop();
else if(!st.empty() && s[i] == ']' && st.top() == '[')
st.pop();
else if(!st.empty() && s[i] == '}' && st.top() == '{')
st.pop();
else
return false;
}
return st.empty();
}
};
沒有留言:
張貼留言