stavros-s
2/22/2013 - 8:05 AM

Find common prefix from a list of strings.

Find common prefix from a list of strings.

    
    
    public static String findCommonPrefix(List<String> strings)
    {
        
        if (strings.size() == 0)
            return "";
        
        
        String prefix = strings.get(0);
        for (int i = 1, s = strings.size(); s > i; i++)
        {
            
            String str = strings.get(i);
            
            for (int j = 0, l = Math.min(prefix.length(), str.length()); l > j; j++)
            {
                
                if (prefix.charAt(j) != str.charAt(j))
                {
                    prefix = prefix.substring(0, j);
                    break;
                }
                
            }
            
        }


        return prefix;
    }