每日算法题:19.6.29

题目:

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

示例:

输入: ["flower","flow","flight"]

输出: "fl"

代码:

public class Test10 {
    public static void main(String[] args) {
        String[] test = new String[]{"c","c"};
        String s = new Test10().longestCommonPrefix(test);
        System.out.println(s);
    }
    public String longestCommonPrefix(String[] strs) {
        if (strs.length==0) {
            return "";
        }
        if (strs.length==1) {
            return strs[0];
        }
        int minLength  =strs[0].length();
        int number =0;
        for (String str : strs) {
            if (str.length()<minLength) {
                minLength = str.length();
            }
            number++;
        }
        String result = "";

        for (int i = 1; i <= minLength; i++) {
            boolean flag =false;
            for (int j = 1; j < number; j++) {
                if (!strs[0].substring(0,i).equals(strs[j].substring(0,i))) {
                    flag = true;
                    break;
                }
            }
            if (flag==false) {
                result = strs[0].substring(0,i);
            }else{
                break;
            }
        }

        return result;
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值