Longest Common Prefix Scan

Scan column by column to keep only the characters every string shares, so grouped keys like deploy-api and deploy-web reduce to their deploy- stem.

JavaCli Tooling

Code

snippet
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")) + "]");
    }
}

How the snippet works

Longest Common Prefix Scan reduces to the class CommonPrefix and the functions commonPrefix and main.

Repetition is confined to for (String other : values.subList(1, values.size())) — the rest of the file is straight-line.

Using it

Entry signature: static String commonPrefix(List<String> values)

The demo flow inside main is commonPrefix — run the file to see it end to end.

Key statements

return first.substring(0, max);

Interactive Tools for This Topic

FAQ

How do you run Longest Common Prefix Scan?
This is a complete program, not a library excerpt — execution starts at the top.