Topic describes

Write a function to find the longest public prefix in an array of strings. Returns an empty string if no common prefix exists"". The sample1: Input: STRS = ["flower"."flow"."flight"] output:"fl"The sample2: Input: STRS = ["dog"."racecar"."car"] output:""Explanation: The input does not have a common prefix.Copy the code

Answer key

Take the first item, and start the second item with startsWith to see if it startsWith the string taken from the first item

const longestCommonPrefix = function (strs) {
  if(! strs || ! strs.length) {return ' ';
  }
  const str = strs[0];
  let index = 0;
  while (index < str.length) {
    // Truncate the prefix from the first item
    const prefix = str.slice(0, index + 1);
    // Check whether the following items all contain this prefix
    for (let i = 1; i < strs.length; i++) {
      // Returns the result if it does not start with this prefix
      if(! strs[i].startsWith(prefix)) {return str.slice(0, index);
      }
    }
    index++;
  }
  return str;
};

longestCommonPrefix(); / / ""
longestCommonPrefix([]); / / ""
longestCommonPrefix(["flower"."flow"."flight"]); // "fl"
longestCommonPrefix(["dog"."racecar"."car"]); / / ""
longestCommonPrefix(["dog"]); // "dog"

Copy the code