【问题标题】:Get longest perfect matches between two strings javascript获取两个字符串javascript之间最长的完美匹配
【发布时间】:2020-10-06 11:49:15
【问题描述】:

这是我们的字符串:

const a = "your majesty they are ready";
const b = "your highness they are ready";

我想得到一个数组,其中包含两个字符串之间最长的完全匹配。

所以对于第一个字符串,我们会得到:

[ ["your"], ["they are ready"] ]

NOT得到最短匹配的这个结果:

[ ["your"], ["they"], ["are"], ["ready"] ]

对我来说,进行单词匹配是一件容易的事。但我需要帮助找出一个合适的解决方案,以获得尽可能长的精确匹配......

顺便说一句,我正在使用这个函数来检查完全匹配:

// exactMatch("I was sent","sent") returns true And exactMatch("I was sentt","sent") returns false
function exactMatch(ref,compare) {
    return new RegExp("\\b" + ref + "\\b").test(compare);
}

注意:我不想要最长的匹配...我想要所有可能最长的匹配。

【问题讨论】:

标签: javascript


【解决方案1】:

类似这样的:

function exactMatch(a, b) {
  a = a.split(' ');
  b = b.split(' ');
  let s = [];
  let out = [];
  let x = a.map(x => b.includes(x) ? x : null);
  x.forEach((v) => {
    if (v == null) {    
    out.push(s);
      s = [];
    } else {
      s.push(v);
    }
  });
  out.push(s);
  out = out.map(x => x.join(' ')).filter(x => x);
  return out;
}
let a = "your majesty they are ready";
let b = "your highness they are ready";
let c = exactMatch(a, b);
console.log(c);

a = "your majesty they are ready, but this is another test";
b = "your highness they are ready, yet this is another test";
c = exactMatch(a, b);
console.log(c);

a = "hello your majesty they are ready, but this is another test";
b = "hi your highness they are ready, yet this is another test";
c = exactMatch(a, b);
console.log(c);

a = "hello your majesty they are ready, but this is another test made";
b = "hi your highness they are ready, yet this is another test completed";
c = exactMatch(a, b);
console.log(c);

【讨论】:

  • 错了,用重复词试试let a = "your majesty they are ready and they are here for us"; let b = "your highness they are ready ands they are here for us";
  • 很好,我写的解决方案真的很相似:)
  • 嗯...完成...,,
  • @Peter Darmis :请也回答这个问题:老实说,你是如何在 javascript 中达到这个掌握水平的......你有什么资源建议我使用能够使用简单的 javascript 语法来工作遇到这种复杂的数据处理问题?
  • @SaraRee 谢谢你,我不知道我是否掌握了Javascript,我每天都在努力学习。好消息是我每天都能学到一些新东西。这个网站不仅是一个良好的开端。此外,还有更多的网站提供您可以在线进行的挑战和测试(hackerrank、codility)。我还喜欢阅读 MDN 文档、很多关于 Google Developers 的有趣文章以及 css-tricks.com 中关于 CSS 的精彩示例。不仅如此。互联网是一个庞大的图书馆,你可以找到一切。
猜你喜欢
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2022-01-19
  • 2019-04-22
相关资源
最近更新 更多