This is the 9th day of my participation in The August More Text Challenge.

The longest common prefix is the longest common prefix.

1. 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"]Copy the code

Example 2:

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

Source: LeetCode link: leetcode-cn.com/problems/lo… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Second, train of thought analysis

Given this problem, we should consider whether iterating over one of the items with the same bit as the other strings is equal.

If the array passed is empty, the empty string is returned; If it is not empty, we can take the first item of the array as the base prefix to compare it with subsequent items.

We can use shift to get the first item out of the array so that the rest of the array doesn’t contain that item. Then use a for loop starting at I =0 to iterate through the remaining items in turn. The for loop continues to nest a layer of for starting at j=0, with the inner loop condition j < the length of the base prefix &&j < the length of the current item.

The inner loop takes the JTH bit of each item and compares it with the JTH bit of the base prefix. If it is different, it means that the match failed. It takes the current j and intercepts the base prefix using the string substr method, which is the longest public prefix passed into the array.

Third, JavaScript implementation code

/ * * *@param {string[]} strs 
 * @return {string}* /
var longestCommonPrefix = function (strs) {
    if (strs.length === 0) return ' ';
    let prefix = strs.shift();
    for (let i = 0; i < strs.length; i++) {
        const cur = strs[i];
        let j = 0;
        for (; j < prefix.length && j < cur.length; j++) {
            if(prefix[j] ! == cur[j]) {break;
            }
        }
        prefix = prefix.substr(0, j);
    }
    return prefix;
};
Copy the code

Four,

The front end is long and long. We are all on the road. We hope to communicate with our friends and make progress together. Keep updating ing…..