leetcode 第十四题的简单算法分析(英文)

14th question from LeetCode

public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String carry = "";
        carry = strs[0];
        //set i to traverse the String array
        for (int i = 1; i < strs.length; i++) {
            while(strs [i].indexOf(carry) != 0){
                if (carry.charAt(0) != strs [i].charAt(0)) break;
                //this loop will continue while the carry string is not included
                //in the current string && overlaps from the beginning
                carry = carry.substring(0, carry.length()-1);//cut short char by char
                if (carry.isEmpty()) break;
                //this means carry is not included in the current string at all
            }
        }
        return carry;
    }

so the idea we use here is to set the first element of the strs[ ] as the carry string , then to shorten the in the loop while the carry string is not only included in the current string but also overlaps from the begging

Thus the carry string which is the first sting of the array will be shorten again and again to fit the requirements

of course it is ok for us to use other ideas to fix this question , just be careful the arrays out of bounds error if you wants to use double “for” loop

god damn it, this is my first algorithm analysis blog and I don’t know what the hell I’m talking.
plus : forgive my funny English…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值