Get longest Common Prefix - Java java.util

Java examples for java.util:List Compare

Description

Get longest Common Prefix

Demo Code


//package com.java2s;

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        List paths = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(longestCommonPrefix(paths));
    }/*  www. ja v  a2s .co m*/

    public static <T> int longestCommonPrefix(List<List<T>> paths) {
        int[] lengths = new int[paths.size()];
        int minLength = Integer.MAX_VALUE;
        for (int i = 0; i < paths.size(); ++i) {
            int len = paths.get(i).size();
            lengths[i] = len;
            if (len < minLength)
                minLength = len;
        }

        int longestCommonPrefix = 0;
        while (longestCommonPrefix < minLength) {
            List<T> headPath = paths.get(0);
            for (List<T> path : paths) {
                if (!headPath.get(longestCommonPrefix).equals(
                        path.get(longestCommonPrefix))) {
                    return longestCommonPrefix;
                }
            }
            ++longestCommonPrefix;
        }
        return longestCommonPrefix;
    }
}

Related Tutorials