
注意三个cases
js
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
const st = []
for (const c of s) {
if (c === '(' || c === '[' || c === '{') {
st.push(c)
} else {
// ) ] }
// 如果栈为空一定不匹配
if (st.length === 0) {
return false
}
const t = st.pop()
if (c === ')' && t !== '(') {
return false
} else if (c === ']' && t !== '[') {
return false
} else if (c === '}' && t !== '{') {
return false
}
}
}
if (st.length) {
return false
}
return true
}长度不为双数直接返回False
python
if n % 2 != 0:
return Falsestack为空直接返回False,如果栈为空一定不匹配
python
else:
if stack == []:
return False判断最后stack为空
python
return True if stack == [] else False