javascript - How to find the longest common prefix in an array of strings? - Stack Overflow

I'm trying to solve this using the .every method but it's not returning true and therefore it

I'm trying to solve this using the .every method but it's not returning true and therefore it's not adding onto my string and I'm not sure why.

var longestCommonPrefix = function(arr) {
  if (arr.length === 0) {
    return undefined;
  }
  let result = '';
  for (let i = 0; i < arr.length; i++) {
    if (arr.every(x => arr[i].charAt(i) === x)) {
      result += arr[i].charAt(i);
    }
  }
  return result
}

console.log(longestCommonPrefix(["flower", "flow", "flight"])); //fl

I'm trying to solve this using the .every method but it's not returning true and therefore it's not adding onto my string and I'm not sure why.

var longestCommonPrefix = function(arr) {
  if (arr.length === 0) {
    return undefined;
  }
  let result = '';
  for (let i = 0; i < arr.length; i++) {
    if (arr.every(x => arr[i].charAt(i) === x)) {
      result += arr[i].charAt(i);
    }
  }
  return result
}

console.log(longestCommonPrefix(["flower", "flow", "flight"])); //fl

Share Improve this question edited Apr 12, 2021 at 23:01 custommander 19.1k6 gold badges69 silver badges93 bronze badges asked Apr 12, 2021 at 21:19 Juan GomezJuan Gomez 193 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You need to iterate over one string, not over the whole array: check if the first character of the string is present everywhere, then the second character, etc:

var longestCommonPrefix = function(arr) {
  if (arr.length === 0) {
    return undefined;
  }
  let result = '';
  for (let i = 0; i < arr[0].length; i++) {
    if (arr.every(x => x.charAt(i) === arr[0][i])) {
      result += arr[i].charAt(i);
    } else break;
  }
  return result;
}

console.log(longestCommonPrefix(["flower", "flow", "flight"])); //fl

Your use of Array.every is along the right lines. You want to check that every string in the array has the same character at position i. I think you got confused when you named the parameter x, when it is in fact a string :)

var longestCommonPrefix = function(words) {
  if (words.length === 0) {
    return "";
  }
  
  const letters = [];
  const lengthOfShortestWord = Math.min(...words.map(word => word.length));
  
  for (let i = 0; i < lengthOfShortestWord; i++) {
    const char = words[0][i];
    if (words.every(word => word[i] === char)) {
      letters.push(char);
    } else {
      break;
    }
  }
  return letters.join("");
}

console.log(longestCommonPrefix(["flower", "flow", "flight"])); //fl

Unless I am mistaken the longest prefix is never going to be greater than the smallest string in the array.

In this case "fl" is both the smallest string and the longest mon prefix:

["flower", "fl", "flight"]

So start with finding the smallest string in arr:

let [sm] = [...arr].sort((a, b) => a.length - b.length);

Then check that all strings in arr start with sm:

arr.every(str => str.startsWith(sm));

If that isn't the case then shorten sm by one character:

sm = sm.slice(0, -1);

And keep going until you eventually find the longest prefix or sm bees an empty string:

const prefix = arr => {
  let [sm] = [...arr].sort((a, b) => a.length - b.length);
  while (sm && !arr.every(str => str.startsWith(sm))) sm = sm.slice(0, -1);
  return sm;
};

The most important is what @CertainPerformance said: "You need to iterate over one string" and with this logic you can use something like this:

var longestCommonPrefix = (strs) => {
    if (strs.length === 0) return '';

    let lettersInCommon = '';

    for (let i = 0; i < strs[0].length; i++) {
        if (strs.every(str => str.charAt(i) === strs[0][i])) {
            lettersInCommon += strs[0][i];
        } else {
            break;
        }
    }

    return lettersInCommon;
};

console.log(longestCommonPrefix(["flower","flow","flight"]))

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744837076a4596329.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信