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

If there is no common prefix, the empty string "" .

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix for the input.

Problem-solving ideas

The first solution is to compare one by one, first compare the longest common prefix of the first and second strings, then use this prefix to compare with the third string, and so on.

function longestCommonPrefix(strs) {
  return strs.reduce((accu, cur) => {
    let prefix = "";
    for (let i = 0; i < accu.length; i++) {
      if (accu[i] === cur[i]) {
        prefix += accu[i];
      } else {
        return prefix;
      }
    }
    return prefix;
  })
}
If you use reduce if you do not specify the initial value, you must ensure that the array is not empty. Since this question has explained that the strs is greater than or equal to 1, there is no need to deal with empty values
Time complexity: O(s) , s is the sum of the number of characters in all strings
Space complexity: O(1)

The above method is easy to think of, but a lot of traversal operations are required, and the time complexity is high. The second method is to compare only the longest common prefix of the largest and smallest strings. The largest and smallest mentioned here refer to the order of ACSII encoding, for example, ab less than abc , abc less than abcd , and abcd less than ac . Then abc and ab and maximum ac must be the common prefix of abcd .

function longestCommonPrefix(strs) {
  let min = 0, max = 0;
  for (let i=0; i<strs.length; i++) {
    if (strs[min] > strs[i]) {
      // 记录最小字符串下标
      min = i;
    }
    if (strs[max] < strs[i]) {
      // 记录最大字符串下标
      max = i;
    }
  }
  for (let i=0; i<strs[min].length; i++) {
    if (strs[min].charAt(i) !== strs[max].charAt(i)) {
      return strs[min].substring(0, i);
    }
  }
  return strs[min];
}
Time complexity: O(n+m) , n is the length of the array, m is the length of the shortest character string array
Space complexity: O(1)

一杯绿茶
199 声望17 粉丝

人在一起就是过节,心在一起就是团圆