LeetCode刷题笔记 - 14. 最长公共前缀

该昵称无法识别

共 11442字,需浏览 23分钟

 · 2021-03-14

学好算法很重要,然后要学好算法,大量的练习是必不可少的,LeetCode是我经常去的一个刷题网站,上面的题目非常详细,各个标签的题目都有,可以整体练习,本公众号后续会带大家做一做上面的算法题。

官方链接:https://leetcode-cn.com/problemset/all/

一、题意

难度:简单

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

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

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

示例

输入:strs = ["flower","flow","flight"]
输出:"fl"

输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

提示:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

二、解题

方法一:横向扫描

思路:

  • 依次遍历字符串数组
  • 将每两个字符串进行比较,更新共同前缀

代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        // 边界判断
        if(strs == null || strs.length == 0 || "".equals(strs[0])) return "";

        // 取一个字符串做前缀用以判断
        StringBuilder pre = new StringBuilder(strs[0]);
  
        // 遍历后续字符串
        for(int i = 1; i < strs.length; i++){
            // 更新共同前缀
            while(strs[i].indexOf(pre.toString()) != 0){
                pre.deleteCharAt(pre.length() - 1);
                if(pre.length() == 0return "";
            }
        }
  // 返回结果
        return pre.toString();
    }
}

复杂度分析:

  • 时间复杂度:O(mn)
  • 空间复杂度:O(1)

后续题解来源:https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode-solution/

方法二:纵向扫描

思路:

  • 从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同
  • 如果相同则继续对下一列进行比较
  • 如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。

代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        // 边界判断
        if (strs == null || strs.length == 0) {
            return "";
        }
        int length = strs[0].length();
        int count = strs.length;
        // 遍历字符串数组
        for (int i = 0; i < length; i++) {
            char c = strs[0].charAt(i);
            // 遍历其余字符串同位元素
            for (int j = 1; j < count; j++) {
                // 如果不相同,则截取当前列之前的部分
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }
        // 返回结果
        return strs[0];
    }
}

复杂度分析:

  • 时间复杂度:O(mn)
  • 空间复杂度:O(1)

方法三:分治

思路:

  • 将相同的问题分解成若干个小问题
  • 两两比较获取共同前缀

代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        // 边界判断
        if (strs == null || strs.length == 0) {
            return "";
        } else {
            // 返回结果
            return longestCommonPrefix(strs, 0, strs.length - 1);
        }
    }

    public String longestCommonPrefix(String[] strs, int start, int end) {
        // 边界判断
        if (start == end) {
            return strs[start];
        } else {
            // 分治
            int mid = (end - start) / 2 + start;
            String lcpLeft = longestCommonPrefix(strs, start, mid);
            String lcpRight = longestCommonPrefix(strs, mid + 1, end);
            // 统计前缀
            return commonPrefix(lcpLeft, lcpRight);
        }
    }

    public String commonPrefix(String lcpLeft, String lcpRight) {
        int minLength = Math.min(lcpLeft.length(), lcpRight.length());
        for (int i = 0; i < minLength; i++) {
            // 两两比较字符串同位元素
            if (lcpLeft.charAt(i) != lcpRight.charAt(i)) {
                return lcpLeft.substring(0, i);
            }
        }
        // 返回结果
        return lcpLeft.substring(0, minLength);
    }
}

复杂度分析:

  • 时间复杂度:O(mn)
  • 空间复杂度:O (mlogn)

方法四:二分查找

思路:

  • 每次取查找范围的中间值 mid,判断每个字符串的长度为 mid 的前缀是否相同
  • 如果相同则最长公共前缀的长度一定大于或等于 mid
  • 如果不相同则最长公共前缀的长度一定小于 mid
  • 通过上述方式将查找范围缩小一半,直到得到最长公共前缀的长度。

代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        // 边界判断
        if (strs == null || strs.length == 0) {
            return "";
        }
        int minLength = Integer.MAX_VALUE;
        for (String str : strs) {
            // 得到最短的字符串长度
            minLength = Math.min(minLength, str.length());
        }
        int low = 0, high = minLength;
        while (low < high) {
            // 二分查找
            int mid = (high - low + 1) / 2 + low;
            if (isCommonPrefix(strs, mid)) {
                low = mid;
            } else {
                high = mid - 1;
            }
        }
        // 返回结果
        return strs[0].substring(0, low);
    }

    public boolean isCommonPrefix(String[] strs, int length) {
        String str0 = strs[0].substring(0, length);
        int count = strs.length;
        // 遍历后续字符串
        for (int i = 1; i < count; i++) {
            String str = strs[i];
            // 两两比较当前位置元素是否相等
            for (int j = 0; j < length; j++) {
                if (str0.charAt(j) != str.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }
}

复杂度分析:

  • 时间复杂度: O(mnlogm)
  • 空间复杂度:O (1)

我的github上有大量计算机类相关电子书籍,都是通过网络中众多好心人分享所搜集到了,有需要的小伙伴可以到下面两个地址自取哦~ https://github.com/unidentifiable/java-other-books https://gitee.com/unidentifiable/java-other-books

- END -


浏览 29
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报