Lintcode784 The Longest Common Prefix II

本文介绍了一种求解给定字符串列表与目标字符串之间的最长公共前缀的问题,并提供了一个具体的算法实现。通过实例展示了如何找出最长公共前缀及其长度。

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

题目

Given n strings and a target string, output the maximum length of the longest common prefix of the target string with the given n strings.

example

Give [“abcba”,”acc”,”abwsf”],target = “abse”,return 2.
Explanation:
The longest common prefix of “abse” and “abcba” is “ab”, and the length is 2. The longest common prefix of “abse” and “acc” is “a”, and the length is 1. The longest common prefix of “abse” and “abwsf” is “ab”, and the length is 2. max(2,1,2) = 2.
Give [“aaa”,”bbb”,”aabb”],target = “aaab”,return 3.
Explanation:
The longest common prefix of “aaab” and “aaa” is “aaa”, and the length is 3. The longest common prefix of “aaab” and “bbb” is “”, and the length is 0. The longest common prefix of “aaab” and “aabb” is “aa”, and the length is 2. max(3,0,2) = 3.

答案

public class Solution {
    /**
     * @param dic: the n strings
     * @param target: the target string
     * @return: The ans
     */
    public int the_longest_common_prefix(List<String> dic, String target) {
        // write your code here
        int res = 0;
        for (int i = 0; i < dic.size(); i++) {
            for (int j = Math.min(dic.get(i).length(), target.length()); j >= 0; j--) {
                String temp = dic.get(i).substring(0, j);
                if (target.substring(0, j).equals(temp)) {
                    if(j > res) {
                        res = j;
                    }
                }
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值