题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Fcompany
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*/
function isValid( s ) {
// write code here
let stateMap = {
'(': 1,
')': -1,
'{': 2,
'}': -2,
'[': 3,
']': -3,
}
let state = []
for (let k of s) {
if (stateMap[k] > 0) {
state.unshift(stateMap[k])
} else {
if (state.length === 0) {
state.unshift(stateMap[k])
break
}
if (state[0] + stateMap[k] !== 0) {
break
} else {
state.shift()
}
}
}
if (state.length === 0) {
return true
}
return false
}
module.exports = {
isValid : isValid
};
借鉴有限状态自动机的思路,初始状态为有效,非初始状态为无效,只是这里的状态并不有限,可以看成是借数组管理的“有限状态”