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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How do you run Longest Common Prefix Scan?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.