First, understand the topic

14. Longest public prefix

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

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

Example:

Input: STRS = ["flower"."flow"."flight"] output:"fl"
Copy the code

2. How to solve the problem

In order to solve the problem, we should write down the following ideas:

  • Iterate over the first element in the array, then compare the first element with other elements;
  • withevery()Method to judge the corresponding position of the letter is equal, equal then record, according to this progressive.

Three, code implementation

Based on the above solution, we will use JS to implement this problem. The specific implementation code is as follows:

/ * * * *@param {array}} STRS string array */
let longestCommonPrefix = function(strs){
    // 1. It is used to store the first string in the array
    let str = strs[0];
    // 2. Check whether the length of the first string is empty.
    STRS == [] = STRS == [] = STRS == []
    if(! str){return ' ';
    }
    // 3. Store the result of the longest prefix
    let res = ' ';
    // 4. Iterate over all elements of the first string
    for(i = 0; i < str.length; i++){
        4.1 Define a flag as a Boolean value
        The every() method is used to check whether all elements of an array meet the specified criteria
        // the every method iterates through the array STRS. After iterating, we get item. After we get item, we iterate through each string one by one to see if it matches the elements in the first string
        let flag = strs.every(item= > item[i] === str[i]);
        if(flag){
            // 4.2 If multiple strings have the same letter of the subscript value, the stack continues
            res += str[i];
        }else{
            //4.3 Jump out of the loop if the prefix is different
            returnres; }}return res;
}
Copy the code

The longest common prefix is the longest common prefix.

We’ll see you next time at 👋👋👋