Title description:

Write a function to find the longest public prefix in an array of strings, returning the empty string “” if none exists. And we assume:

  • All inputs contain only lowercase lettersa-z
  • Consider an empty array.

Example:

Input: [" Java "and" javascript ", "json"] output: "j" type: [" dog ", "racecar", "car"] output: "" input: [" flower", "flow", "flight"] output: "fl"Copy the code

Method analysis:

In analyzing such problems, our thinking should be roughly as follows:

  • If the string array is empty, we simply return an empty string.

  • If the string array has only one entry, such as [“qianduan”], then simply return the string.

  • If the array of strings has more than one item, we can get the first item first and then compare each character of the first item to the corresponding position of each character of the following string. If there are differences, no further judgment will be conducted, but directly return the results; If the characters are the same at the corresponding positions in this iteration, it is logged.

    var longestCommonPrefix = function(strings) { var firstStrs = strings[0]; var result =”; if(! strings.length){ return result; } for (var i = 0; i < firstStrs.length; i++) { for (var j = 1; j < strings.length; j++) { if(firstStrs[i] ! = strings[j][i]){ return result; } } result += firstStrs[i]; } return result; };

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