题目分析:括号匹配的问题,使用栈就很容易实现
代码分析:
C++:
bool isValid(string s) {
stack<char> st;
if (s.length() == 0) return false;
for(char c : s){
if (c == '(' || c == '{' || c == '[')
st.push(c);
else{
if(c == ')' && st.top() != '(') return false;
if(c == '}' && st.top() != '{') return false;
if(c == ']' && st.top() != '[') return false;
st.pop();
}
}
return st.empty();
}
python:
def isvalid(s):
stack = []
d = { //字典
"{": "}",
"[": "]",
"(": ")"
}
for x in s:
if x in d:
stack.append(d[x])
else:
if len(stack) != 0:
top_element = stack.pop() //出栈
if x != top_element:
return False
else:
continue
else:
return False
return len(stack) == 0