简体   繁体   English

查找也是字符串后缀的最长前缀-Javascript

[英]Find Longest Prefix That is Also a Suffix in String - Javascript

Link to codewars challenge 链接到Codewars挑战

I need to return the length of the longest prefix that is also a suffix of a string in Javascript. 我需要返回最长前缀的长度,该长度也是Javascript中字符串的后缀。

As far as I understand, the prefixes in "abcd" are: 据我了解, "abcd"中的前缀是:

['a', 'ab', 'abc']

And the suffixes in "abcd" are: 并且"abcd"的后缀为:

[ 'bcd', 'cd', 'd' ]

So the length of the longest prefix that is also a suffix in "abcd" in this case is 0, because there are no prefixes that are also suffixes in "abcd" . 因此,在这种情况下,最长前缀也是"abcd"的后缀的长度为0,因为没有前缀也是"abcd"后缀。

So far I've been able to figure out how to get the suffixes into an array for comparison, but not the prefixes. 到目前为止,我已经能够弄清楚如何将后缀放入数组进行比较,而不是前缀。

function returnLongestPrefixAndSuffix(string) {

  let prefixes = [];
  let suffixes = [];

  for (let i = 0; i < string.length -1; i++) {
    prefixes.push(string.slice(i));
  }

  for (let i = 1; i < string.length; i++) {
    suffixes.push(string.slice(i));
  }

  return prefixes + " " + suffixes;

}

console.log(returnLongestPrefixAndSuffix("abcd"));

I'm not grasping the concept of how to start at the beginning of a string and add a larger element to the array each time by one character, excluding the element that would include the last one. 我没有掌握如何从字符串的开头开始,并且每次都以一个字符向数组添加一个较大的元素的概念,但不包括将包含最后一个元素的元素。

Please follow my current logic if possible. 如果可能,请遵循我当前的逻辑。

EDIT : My code now looks like this: 编辑 :我的代码现在看起来像这样:

function solve(string) {

    let prefixes = [];
    let suffixes = [];
    let includedList = [];

    for (let i = 1; i < string.length; i++) {
      prefixes.push(string.slice(0, i));
    }

    for (let i = 1; i < string.length; i++) {
      suffixes.push(string.slice(-i));
    }

    console.log(prefixes);
    console.log(suffixes);

    for (let i = 0; i < prefixes.length; i++) {
        let element = prefixes[i];
        if (suffixes.includes(element) === true) {
            includedList.push(element);
        }
    }

    console.log(includedList);
    if (includedList.length === 0) {
        return 0;
    }
    else {
        let overlap = prefixes.filter(value => suffixes.includes(value));
        console.log(overlap);
        let longest = includedList.sort(function (a, b) { return b.length - a.length; })[0];
        return longest.length;
    }
}

console.log(solve("abcdabc"));

And this is passing 10049 test but failing 163 tests on codewars. 这通过了10049测试,但在代码战中没有通过163测试。 I still do not know what to do with the overlap variable or how to exclude overlaps from the includedList array. 我仍然不知道如何处理overlap变量或如何从includedList数组中排除重叠。

function solve(string) {

    for (let i = Math.floor(string.length / 2); i > 0; i--) {

        let prefix = string.slice(0, i);
        let suffix = string.slice(-i);

        if (prefix == suffix) {
            return i;
        }
    }
    return 0;
}

console.log(solve("abcdabc"));

To account for the overlap, initialize your for-loop like this: 为了解决重叠问题,请像下面这样初始化for循环:

let i = Math.floor(string.length / 2)

That will initialize the for-loop at the half-way point in your string, so that you can count down and compare whether or not the prefix == the suffix, starting with the longest. 这将在字符串的中点初始化for循环,以便您可以递减并比较前缀==后缀(从最长的开始)。

You could return prefix.length , but that will be the same thing as i . 您可以返回prefix.length ,但这将与i相同。

Also, be sure to return 0 outside of the for-loop. 另外,请确保在for循环之外return 0 Because if you try: 因为如果您尝试:

if (prefix != suffix) {
    return 0;
   }

inside of the for-loop, it will stop counting right there. 在for循环内部,它将在那里停止计数。

To get the prefixes, you can use the second argument of .slice : 要获取前缀,可以使用.slice的第二个参数:

  string.slice(0, i)

Note that to get the suffixes, you could also take the string from the end: 请注意,要获取后缀,还可以从结尾处获取字符串:

  string.slice(-i)

There is no sense in collecting prefixes and suffixes in arrays, just search for the biggest i where the suffix equals the prefix. 收集数组中的前缀和后缀是没有意义的,仅搜索后缀等于前缀的最大i即可。

Please see the documentation of the slice function, it may take a second argument: https://www.w3schools.com/jsref/jsref_slice_string.asp 请参阅slice函数的文档,它可能需要第二个参数: https : //www.w3schools.com/jsref/jsref_slice_string.asp

So following your logic, one way to get prefixes would be to: 因此,遵循您的逻辑,获取前缀的一种方法是:

for (let i = 1; i <= string.length; i++) {
  prefixes.push(string.slice(0, i));
}

EDIT: Your newest code doesn't work because of two reasons: 编辑:您的最新代码不起作用,因为两个原因:

  1. You may end up with includedList being empty, but you still try to get first element out of it. 您可能最终将includedList为空,但是您仍然尝试从中获取第一个元素。

  2. You don't take overlaps into consideration. 您无需考虑重叠。 For the input aaa the correct result is a since prefix aa overlaps with the corresponding suffix. 对于输入aaa ,正确的结果是a因为前缀aa与相应的后缀重叠。 In other words the result can't be longer than half the length of the input. 换句话说,结果不能超过输入长度的一半。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM