【问题标题】:Javascript recursive exampleJavascript递归示例
【发布时间】:2022-11-03 01:39:55
【问题描述】:

我最近有一次面试,你必须递归地遍历一个字符串,如果它包含AB || BA || CD || DC,它必须从数组中删除。您将递归地检查这一点,因为从ACDBB 中删除CD 会给您一个AB,然后您必须删除它才能将B 作为字符串返回。

这就是我所拥有的,当我对其进行测试时,我发现它在循环深处提出了正确的答案,但它永远不会回到顶部。

我错过了什么?

const LETTERS = [/AB/g, /BA/g, /CD/g, /DC/g];

const stringGame = (string) => {
    
    let newString = '';

    if(string.length <= 1) return string;


    LETTERS.forEach(regExToCheck => {
        if(string.match(regExToCheck)) {
            newString = string.replace(regExToCheck, '')
        }
        stringGame(newString);
    })

    return newString
}

// Expect answer: CAACC
console.log(stringGame('ABDCABCABAAABCCCD'))

【问题讨论】:

    标签: javascript recursion


    【解决方案1】:

    stringGame 函数没有副作用,所以这里循环中的行:

    stringGame(newString);
    

    不做任何事情 - 您需要将递归调用的结果传达回外部级别。

    解决此问题的更好方法是将LETTERS 组合成一个正则表达式,然后用空字符串替换所有匹配项,直到替换不产生任何更改。

    const LETTERS = [/AB/g, /BA/g, /CD/g, /DC/g];
    const pattern = new RegExp(
      LETTERS
        .map(re => {
          const str = String(re);
          return str.slice(1, str.length - 2);
        })
        .join('|'),
    );
    
    const stringGame = (string) => {
      const newString = string.replace(pattern, '');
      return newString === string
        ? string
        : stringGame(newString);
    }
    
    // Expect answer: CAACC
    console.log(stringGame('ABDCABCABAAABCCCD'))

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 1970-01-01
      • 2019-08-02
      • 2022-01-19
      • 2011-03-15
      • 2012-12-25
      • 2019-10-24
      • 2010-09-11
      • 2017-10-05
      相关资源
      最近更新 更多