检查 JavaScript 中括号的有效性

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 7:40:17

我们需要编写一个 JavaScript 函数,该函数接受仅包含字符 − 的字符串 str

'(', ')', '{', '}', '[' 和 ']'

我们的函数应该确定输入的字符串是否有效。

如果满足以下条件,则输入的字符串有效

  • 左括号必须用相同类型的括号关闭。

  • 左括号必须以正确的顺序关闭。

例如 −

  • "()" 是有效的括号

  • "()[]{}" 是有效的括号

  • "(]" 是无效的括号

示例

其代码为 −

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

相关文章


有用资源