首页 > 解决方案 > 找出一个字符串在一组字符串中变得唯一之前需要多少

问题描述

这很难解释,但我会尽力...

我有一个字符串数组。让我们在这里使用一个例子:

var myArray = [
    "hello there my friend robert"
    "hello there friend kimberly"
    "hello friend claire"
    "hi there friend chris"
]

我正在尝试编写一个函数,该函数将确定数组中每个字符串在变得唯一之前需要多少个单词。例如,使用上述数组作为输入,函数应返回以下内容:

[
    "hello there my",
    "hello there friend",
    "hello friend",
    "hi"
]

返回数组中的字符串表示在字符串变得唯一之前每个字符串所需的单词。

例如,该函数为“hello there my friend robert”返回“hello there my”。这是因为“你好”本身是模棱两可的。它可以指“你好,我的朋友罗伯特”或“你好,朋友金伯利”。然而,“你好,我的”只能指“你好,我的朋友罗伯特”。

我完全不知道如何做到这一点。还有其他人知道解决方案吗?

(为简单起见,假设输入字符串没有标点符号并且完全小写。)

标签: javascriptarraysstring

解决方案


我想我对此有一些想法。你可以做的就是像这样存储列表。

{
   'first' : ['hello', 'hello', 'hello', 'hi'],
   'second' : ['there','friend','there'],
   'third' : ['my', 'friend', 'claire'],
   'fourth' : ['robert', 'kimberly', 'chris']
}

现在只需检查这张地图上第一个的计数是否超过一个,那么你必须继续前进,如果计数是一个,你必须停在那里。


推荐阅读