I. Title Description:

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”]

Example 2:

Input: STRS = [“dog”,”racecar”,”car”] Output: “” Explanation: The input does not have a common prefix.

Tip:

Length <= 200 0 <= STRS [I]. Length <= 200 STRS [I] Consists of lowercase letters only

Ii. Analysis of Ideas:

  1. Make the first string a public prefixprefix
  2. withprefixExtract the common prefix from each stringgetPrefix
  3. whenprefixAn empty string indicates that there are no public prefixes, and returnsprefixCan be
  4. The last returnprefixJust a matter of

Iii. AC Code:

/ * * *@param {string[]} strs
 * @return {string}* /
var longestCommonPrefix = function(strs) {
    let prefix = strs[0] | |' ';
    for(let i = 1; i < strs.length; i++) {
        prefix = getPrefix(prefix, strs[i]);
        if(prefix.length === 0) {
            returnprefix; }}return prefix;
};

function getPrefix(commonPrefix, str) {
    let len = Math.min(commonPrefix.length, str.length)
    let prefix = ' '
    for(let i = 0; i < len; i++) {
        if (commonPrefix.charAt(i) === str.charAt(i)) {
            prefix += commonPrefix.charAt(i)
        } else {
            returnprefix; }}return prefix;
}
Copy the code

Iv. Summary:

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign