我们需要编写一个JavaScript函数,该函数接受仅包含字符的字符串str-
'(', ')', '{', '}', '[' and ']'
我们的函数应确定输入字符串是否有效。
输入字符串在以下情况下有效-
开括号必须用相同类型的括号封闭。
开括号必须以正确的顺序关闭。
例如-
“()”是有效的括号
“()[] {}”是有效的括号
“(]”是无效的括号
为此的代码将是-
const str = "()[]{}"; const isValid = (str = '') => { const map=new Map(); map.set('{','}'); map.set('(',')'); map.set('[',']'); const b=[]; for(let i=0;i<str.length;i++){ if(map.has(str.charAt(i))){ b.push(str.charAt(i)); } else{ let pop=b.pop(); if(map.get(pop)!==str.charAt(i)){ return false; } }; }; return b.length===0; }; console.log(isValid(str));
输出结果
控制台中的输出将是-
true false