作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnmav1/ 来源:力扣(LeetCode)

    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    编写一个函数来查找字符串数组中的最长公共前缀。
    如果不存在公共前缀,返回空字符串 “”。

    1. 示例 1
    2. 输入:strs = ["flower","flow","flight"]
    3. 输出:"fl"
    4. 示例 2
    5. 输入:strs = ["dog","racecar","car"]
    6. 输出:""
    7. 解释:输入不存在公共前缀。
    1. /**
    2. * @param {string[]} strs
    3. * @return {string}
    4. */
    5. var longestCommonPrefix = function(strs) {
    6. if (strs.length === 0) {
    7. return ''
    8. }
    9. // 1. 找到最短的值
    10. let min = strs[0];
    11. for (let x of strs) {
    12. if (x.length < min.length) {
    13. min = x;
    14. }
    15. }
    16. // 2. 定义一个指针
    17. let right = min.length;
    18. while (right > 0) {
    19. let prefix = min.slice(0, right);
    20. // 3. every匹配
    21. if (strs.every(item => item.indexOf(prefix) === 0)) {
    22. return prefix;
    23. }
    24. right--;
    25. }
    26. return ''
    27. };

    参考:
    https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode-solution/