← 中文资源

简体中文版本

最长公共前缀逐列扫描

以最短串为界逐列比较,遇到第一列不同就截断:deploy-api 与 deploy-web 归并出共同前缀 deploy-,空列表返回空串。

阅读英文原文

实现说明

活动部件是类 CommonPrefix和函数 commonPrefix、main。 for (String other : values.subList(1, values.size())) 承担全部的逐项处理。

使用要点

  • 运行整个文件:main 会依次驱动 commonPrefix。

常见问题

「最长公共前缀逐列扫描」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

主要签名是 static String commonPrefix(List<String> values)

核心语句

return first.substring(0, max);

代码示例

import java.util.List;

public class CommonPrefix {

    // 逐列扫描:以最短字符串为界,遇第一个不匹配列即截断
    static String commonPrefix(List<String> values) {
        if (values.isEmpty()) {
            return "";
        }
        String first = values.get(0);
        int max = first.length();
        for (String other : values.subList(1, values.size())) {
            max = Math.min(max, other.length());
            for (int i = 0; i < max; i++) {
                if (first.charAt(i) != other.charAt(i)) {
                    max = i;
                    break;
                }
            }
        }
        return first.substring(0, max);
    }

    public static void main(String[] args) {
        System.out.println("[" + commonPrefix(List.of("deploy-api", "deploy-web", "deploy-db")) + "]");
        System.out.println("[" + commonPrefix(List.of("alpha", "beta")) + "]");
        System.out.println("[" + commonPrefix(List.of("same", "same", "same")) + "]");
    }
}