Java Array Common Prefix longestCommonPrefix(String[] strs)

Here you can find the source of longestCommonPrefix(String[] strs)

Description

longest Common Prefix

License

Open Source License

Declaration

public static String longestCommonPrefix(String[] strs) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }/*w  w  w .  j  a v a 2  s .  c  om*/
        int minLen = findMin(strs);
        String str0 = strs[minLen];
        // System.out.println(minLen);
        for (int k = 0; k < str0.length(); k++) {
            for (int i = 0; i < strs.length; i++) {
                String str = strs[i];
                if (str.charAt(k) != str0.charAt(k))
                    return str0.substring(0, k);
            }
        }
        return str0;
    }

    public static int findMin(String[] strs) {
        int result = 0;
        int minLen = 1000;
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].length() < minLen) {
                minLen = strs[i].length();
                result = i;
            }
        }
        return result;
    }
}

Related

  1. longestCommonPrefix(String one, String two)
  2. longestCommonPrefix(String s1, String s2)
  3. longestCommonPrefix(String str1, String str2)
  4. longestCommonPrefix(String... strs)
  5. longestCommonPrefix(String[] strArray)
  6. longestCommonPrefix(String[] strs)
  7. longestCommonPrefix(String[] strs)
  8. longestCommonPrefix(String[] strs)
  9. longestCommonPrefix(String[] strs)