Leetcode|14.Longest Common Prefix最长公共前缀.java

题目

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

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

示例 :

输入: [“flower”,“flow”,“flight”]

输出: “fl”

输入: [“dog”,“racecar”,“car”]

输出: “”

解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z

标签

字符串;递归

解题思路

方法一:横向扫描

依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。如果在尚未遍历完所有的字符串时,最长公共前缀已经是空串,则最长公共前缀一定是空串,因此不需要继续遍历剩下的字符串,直接返回空串即可。

方法二:纵向扫描

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

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

代码

public class Leetcode14_LongestCommonPrefix {
    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        System.out.println(Leetcode14_LongestCommonPrefix.longestCommonPrefix1(strs));
    }


    //方法一:横向扫描:将每两个字符串进行比较后,再将公共部分与第三个比较
    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            result = CommonPrefix(result, strs[i]);
        }
        return result;
    }

    //两个字符串的公共前缀
    public static String CommonPrefix(String str1, String str2) {
        if (str1.length() == 0 || str2.length() == 0) {
            return "";
        }
        //最小公共前缀长度
        int len = Math.min(str1.length(), str2.length());
        //最小公共前缀
        String result;
        for (int i = 0; i < len; i++) {
            if (str1.charAt(i) != str2.charAt(i)) {
                result = str1.substring(0, i);
                return result;
            }
        }
        return str1.substring(0, len);
    }

    //方法二:纵向扫描:将每个字符串第一列进行比较后,再将第二列进行比较,依次类推
    public static String longestCommonPrefix1(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int len = strs[0].length();
        int count = strs.length;
        //行
        for (int i = 0; i < len; i++) {
            //列
            char ch = strs[0].charAt(i);
            for (int j = 1; j < count; j++) {
                if (strs[j].charAt(i) != ch || i == strs[j].length()) {
                    return strs[0].substring(0, i);
                }
            }
        }
        return strs[0];
    }
}

来源:力扣(LeetCode)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦晨涌京

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值