chencl1986/Blog

LeetCode题解:20. 有效的括号,while循环replace,JavaScript,详细注释

chencl1986 opened this issue · 0 comments

阅读更多系列文章请访问我的GitHub 博客

原题链接:https://leetcode-cn.com/problems/valid-parentheses/

解题思路:

  1. 进行while循环,每循环一次替换一对括号。
  2. 如果发现替换之后,替换前后的字符串相等,表示有无效括号。
  3. 如果替换到字符串为空,表示所有括号都有效。
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  while (s.length) {
    const temp = s; // 缓存替换前字符串
    s = s.replace(/(\(\))|(\[\])|(\{\})/, '');

    // 如果替换后字符串与替换前相同,说明存在不成对括号
    if (s === temp) {
      return false;
    }
  }

  // 如果数组为空退出循环,则字符串内都为有小括号
  return true;
};