【问题标题】:Avoid replacement of previous letters with string.replace避免用 string.replace 替换以前的字母
【发布时间】:2021-09-19 07:40:48
【问题描述】:

我正在做一个 CodeWars kata,它根据字母的重复将单词编码为开括号或闭括号。这是link

当单词等于“ ( ( )”时,我的代码可以处理所有测试,但只有一个测试。

我想我发现在最后一个“)”上,由于替换的匹配,第一个“(”被更改为“)”,从而改变了预期的输出。有什么方法可以防止我的输出发生这种不必要的变化?

const duplicateEncode = (word) => {
  let words = word.toLowerCase();
  let obj = {};
  for (let i of words) {
    obj[i] = obj[i] ? obj[i] + 1 : 1;
  }
  for (let i of words) {
    obj[i] === 1
      ? (words = words.replace(i, "("))
      : (words = words.replace(i, ")"));
  }
  return words;
};

预期输出

duplicateEncode(" ( ( )")); // )))))(

我的输出

duplicateEncode(" ( ( )")); // ()))))

【问题讨论】:

标签: javascript string replace parentheses


【解决方案1】:

不要在整个单词上使用 String.replace,你应该直接修改每个字符,或者更好地构造一个新的字符串来返回。

const duplicateEncode = (word) => {
  let words = word.toLowerCase();
  let obj = {};
  for (let i of words) {
    obj[i] = obj[i] ? obj[i] + 1 : 1;
  }
  let out = "";
  for (let i of words) {
    out += obj[i] === 1 ? "(" : ")";
  }
  return out;
};

console.log(duplicateEncode(" ( ( )"));
// )))))(

【讨论】:

  • 在寻求外部帮助后,有人指出了同样的事情,所以确实,我构造了一个新数组。谢谢!!!
猜你喜欢
  • 2013-06-02
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 2012-06-23
  • 2018-04-04
  • 1970-01-01
相关资源
最近更新 更多