Write a function to find the longest public prefix in an array of strings.

Returns the empty string “” if no public prefix exists.

Example 1:

Input: ["flower","flow","flight"] Output: "fl"Copy the code

Example 2:

Input: ["dog","racecar","car"] Output: "" Explanation: The input does not have a common prefix.Copy the code

My algorithm implementation:

/ * * *@param {string[]} strs
 * @return {string}* /
var longestCommonPrefix1 = function (strs) {
  if (strs.length === 0) return "";
  let str = "";
  for (let i = 0; i < strs[0].length; i++) {
    let tempStr = strs[0][i],
      j = 1;
    for (; j < strs.length; j++) {
      if(strs[j][i] ! == tempStr)break;
    }
    if (j === strs.length) {
      str += tempStr;
      j = 1;
    } else {
      break; }}return str;
};
Copy the code

My idea is simple, just compare one by one, and if one satisfies, save it. The more I did, the more problems I exposed, such as the fact that there was only one or two ways I could think of at a time, and they were all general ideas (with very little data structure). Here’s the official solution, and there are many ways to do it, each of which is worth learning, and I plan to revisit data structures and sorting later this week.

Official solution: The longest public prefix

Divide and conquer is almost my blind spot, I will focus on practice later.


Source: LeetCode