leetcode -- longest common prefix

Posted by w4designs on Tue, 07 Jan 2020 08:04:22 +0100

Title: write a function to find the longest common prefix in the string array. Returns the empty string '' if no public prefix exists.

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

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

Learning algorithm, no idea. Four ways of solving problems are found on the Internet, and they are going to try one by one.  

Source of thinking: https://www.aliyun.com/jiaocheng/17602.html

Method 1: traverse horizontally. Take the first string as the standard, judge whether it is a prefix in turn, and if not, subtract one until it is a prefix.

My code:

    var longestCommonPrefix = function( strs ) {
        var maxNum = strs.length - 1; // Array length
        if (maxNum < 0) return ""; // -1 reverse to true
        else if (maxNum === 0) return strs[maxNum];
        else{
            var temp = strs[0]; // Record the first string as LCP (common prefix)
            var num = 1; // Record comparison location
            while(temp){
                if (temp === strs[num] ) {
                    temp = strs[num];
                }else if( temp !== strs[num] ) {
                    var len = temp.length > strs[num].length ? temp.length : strs[num].length;
                    for (var i = 0 ; i < len ; i++) {
                        if (temp.charAt(i) !== strs[num].charAt(i)) {
                            temp = temp.substr(0, i);
                            break;
                        }
                    }
                }
                if (num === maxNum) break; //Judge whether to the last
                else {
                    num++;
                }
            }
        }
        return temp;
    };

Just finished writing, I'm still happy, but I found that when my execution time is 100ms +, it's not a little bit more than others' time on leetcode. After trying the rest of the methods, I went to leetcode to study other people's ideas.

Method 2: longitudinal traversal. Start traversing from the first character until all strings are found with different characters

My code:

    var longestCommonPrefix = function (strs) {
        var maxLen = strs.length;
        if (maxLen === 0) return "";
        if (maxLen === 1) return strs[0];
        var temp = ""; // Store LCP
        var num = null; // Record location
        var str = strs[0];
        for (var i = 0; i < str.length; i++) {
            for (var j = 0 ; j < maxLen - 1; j++) {
                if (strs[j][i] !== strs[j+1][i]) {
                    return temp;
                }
                num = i + 1;
            }
                temp = str.substr(0, num);
        }
        return temp;
    };

This time, it's 30 ms faster than last time. It seems that the speed of choosing different methods will be significantly improved. Algorithms are fun.  

Topics: REST