all articles

leetcode war 14 - Longest Common Prefix

2017-09-26 @sunderls

leetCode js

https://leetcode.com/problems/longest-common-prefix/description/

Write a function to find the longest common prefix string amongst an array of strings.

brutal force

just check the characters one by one, it will lead to O(n*m) complexity.

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    var result = [];
    var char = '';

    if (strs.length === 0) {
        return '';
    }

    for (var i = 0, totalI = strs[0].length; i < totalI; i++) {
        char = strs[0][i];

        for (var j = 1, totalJ = strs.length; j < totalJ; j++) {
            if (strs[j][i] !== char) {
                return result.join('');
            }
        }
        result.push(char);
    }

    return result.join('');
};

it passed. beating 82% submission.

but, how can we improve?