前言
算法题练习记录
题目来源:LeetCode
链接:https://leetcode-cn.com/problems/valid-parentheses一、代码实现
使用“栈”实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>有效的括号</title>
</head>
<body>
<script>
// -----------------------题目---------------------
// 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
//
// 有效字符串需满足:
//
// 左括号必须用相同类型的右括号闭合。
// 左括号必须以正确的顺序闭合。
//
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/valid-parentheses
// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
</script>
<script>
// -----------------------题解---------------------
const s = ['()', '()[]{}', '(]', '([)]', '{[]}'] // 测试用例:true true false false true
for (let i of s) {
console.log(`${ i } - ${ isValid(i) }`)
}
function initMap() {
// 初始化map
let map = new Map()
map.set('(', ')')
map.set('[', ']')
map.set('{', '}')
return map
}
function isValid(s) {
// 左括号入栈顺序应为右括号出栈逆序 --> 入栈"([" --> 出栈"])"
if ((s.length % 2) != 0) {
// 长度为奇数
return false;
}
let map = initMap()
let arr = []
for (let sItem of s) {
// 1.遇到左括号,则将对应的右括号入栈
// 2.若遇到右括号 ->
// (1) 若栈内为空 则 返回false;
// (2) 若栈内非空且栈顶元素不匹配 返回false;
// (3) 若匹配 则 判断下一字符
if (!map.has(sItem.toString())) {
// map.has(sItem.toString()) == true --> 遇到右括号
if (arr.length == 0){
// 栈内为空
return false
} else {
// 栈内非空
if (arr.pop() != sItem) {
return false
}
}
} else {
// 遇到左括号,则将对应的右括号入栈
arr.push(map.get(sItem.toString()))
}
}
// 2.判断arr的长度
// (1) 若为0 则 匹配成功
// (2) 若非0 则 匹配失败
if (arr.length == 0) {
return true
}
return false
}
</script>
</body>
</html>
二、实机演示
总结
LeetCode算法题-有效的括号(JavaScript实现)