Longest Common Prefix

本文介绍了一种寻找字符串数组中最长公共前缀的方法。通过对比第一个和第二个字符串找到初步的公共前缀,然后迭代剩余字符串进一步缩小公共前缀范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Write a function to find the longest common prefix string amongst an array of strings.

Analysis: First compute the common prefix of the first two strings and then use the result compare with the rest of the strings in that array. 

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        String common = "";
        if(strs.length==0) return common;
        if(strs.length==1) return strs[0];
        
        // got common prefix from the first two strings
        String s0 = strs[0];
        String s1 = strs[1];
        for(int i=0; i<(s0.length()<=s1.length()?s0.length():s1.length()); i++) {
            if(s0.charAt(i)==s1.charAt(i)) common+=s0.charAt(i);
            else break;
        }
        if(common=="") return common;
        
        // iterate the rest strings in the array to got the longest common prefix
        for(int j=2; j<=strs.length-1; j++) {
            String temp = "";
            for(int k=0; k<(common.length()<=strs[j].length()?common.length():strs[j].length()); k++) {
                if(common.charAt(k) == strs[j].charAt(k)) {
                     temp += strs[j].charAt(k);
                }
                else {
                    if(k==0) return "";
                    else break;
                }
            }
            common = temp;
        }
        
        return common;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值