编写一个函数来查找字符串数组中的最长公共前缀。


    如果不存在公共前缀,返回空字符串 “”。

    1. var strs1 = ['flower', 'flow', 'flight'];
    2. var strs2 = ['dog', 'racecar', 'car'];
    3. var longestCommonPrefix = function (strs) {
    4. if (strs.length === 0) return '';
    5. let curCommonPrefix = strs[0];
    6. for (let i = 1; i < strs.length; i++) {
    7. let curString = strs[i],
    8. length = Math.min(curCommonPrefix.length, curString.length);
    9. if (length === 0) return '';
    10. for (let j = 0; j < length; j++) {
    11. if (curCommonPrefix[j] != curString[j]) {
    12. curCommonPrefix = curCommonPrefix.substring(0, j);
    13. break;
    14. }
    15. }
    16. curCommonPrefix = curCommonPrefix.substring(0, length);
    17. }
    18. return curCommonPrefix;
    19. };
    20. console.log(longestCommonPrefix(strs1));
    21. console.log(longestCommonPrefix(strs2));