leetcode【简单】14、最长公共前缀(LCP)

在这里插入图片描述
思路1:取第二个和第一个比较,找出最长前缀,然后后面的逐渐遍历比较
find函数:str1.find(str2, beg=0, end=len(string))
检查str2是否在str1中,找得到返回索引,找不到返回-1

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        res=strs[0]
        i=1
        while i<len(strs):
        	#如果res在s[1]中,那就使res一直减少,直到跳出循环
            while strs[i].find(res)!=0:
                res=res[0:len(res)-1]
            i+=1
        return res
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs==null){
            return "";
        }
        String res=strs[0];
        for(String s : strs){
            while(!s.startsWith(res)){
                if(res==null){//可以省略if,如果res为null,while也为true的
                    return "";
                }else{
                    res=res.substring(0,res.length()-1);
                }
            }
        }
        return res;
    }
}

思路2:先排序,直接比较差异最大的第一个和最后一个字符串即可
比思路一快很多

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        strs.sort()#排序默认按字母大小排
        l=len(strs)
        first=strs[0]
        last=strs[-1]
        res=""

        for i in range(len(first)):
            if i<len(last) and first[i]==last[i]:
                res=res+first[i]
            else:
                break
        return res
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        Arrays.sort(strs);
        String first=strs[0];
        String last=strs[strs.length - 1];
        while(!last.startsWith(first)){
            first=first.substring(0,first.length()-1);
        }
        return first;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值