Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chencl1986 opened this issue Aug 25, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

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

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

解题思路:

  1. 成对括号的数量正好是字符串长度的1/2,假设有n对括号。
  2. 循环n次,每次用replace替换掉一组成对括号。
  3. n次之后,如果字符串不为空,即表示有非成对括号存在。
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  // 计算可能的括号对数
  let len = s.length / 2;

  // 每次循环替换掉一组括号
  for (let i = 0; i < len; i++) {
    s = s.replace(/(\(\))|(\[\])|(\{\})/, '');
  }

  // 如果字符串不为空,表示有非成对括号
  return s.length ? false : true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant