【问题标题】:Iterating the same method on a string在字符串上迭代相同的方法
【发布时间】:2021-04-10 07:52:24
【问题描述】:

我有一个字符串,我想迭代 .replace(re,'') 直到我实现并清空 sting ""。如何做到这一点,而不是一遍又一遍地重复相同的方法

var isValid = (s)=> {
   const re = /(\(\))|(\[\])|(\{\})/gi
   return s.replace(re,'').replace(re,'').replace(re,'').replace(re,'') !='' ? false :true
  
};

console.log(isValid("[({(())}[()])]"))

【问题讨论】:

  • 可以replaceAll 帮忙吗?
  • 改写(如果我没记错的话)你想递归地替换/删除具有"valid" 右括号?
  • @Roko C. Buljan 完全正确。
  • 网上有很多帖子讨论解决这类问题。只是谷歌的“平衡括号算法”。他们中的大多数使用堆栈来执行此操作。这是一个讨论此问题的 SO 问题:stackoverflow.com/questions/16874176/….
  • 请注意,堆栈方法在 O(n) 而不是 O(n^2) 中解决了这个问题。

标签: javascript regex


【解决方案1】:

您可以使用 while 循环。

var isValid = (s)=> {
   const re = /(\(\))|(\[\])|(\{\})/gi
   while(re.test(s)) s = s.replace(re, '');
   return s === '';
};

【讨论】:

  • 更好(IMO)while (re.test(s)),因为test 返回一个布尔值。
  • 是的,我认为 while 是答案,尽管从未完全理解。谢谢,真的很感激。
  • @AdeN 没问题。
猜你喜欢
  • 2010-10-08
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多