14. The longest common prefix – LeetCode (leetcode-cn.com)

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:

STRS = ["flower","flow","flight"]Copy the code

Example 2:

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

Tip:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i]Contains only lowercase English letters

Take the first element of STRS as the public prefix, continue if the elements in the corresponding positions of subsequent elements are equal, and return the previous public prefix if they are not equal.

/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { if (strs.length <= 1) return strs[0] if (strs.includes('')) return '' let [comonPrefix, ...restStr] = strs let r = '' for (let i in comonPrefix) { const t = comonPrefix[i] for (let j in restStr) { const jt = restStr[j][i] if (t ! == jt) { return r } if (j == restStr.length - 1) { r += t } } } return r };Copy the code

It passed!

We should be able to optimize space by using Map or regex, o(n ^ 2), o(n), so let’s stop there, let’s go to sleep