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 == null || strs.length == 0)
            return "";

        // length of the smallest string in the array
        // is the upper bound for the possible
        // value of the prefix string
        int minLen = Integer.MAX_VALUE;
        for (String str : strs)
            minLen = (minLen > str.length()) ? str.length() : minLen;

        // main goal: max possible length of prefix
        // is minLen => loop bounds
        for (int i = 0; i < minLen; i++) {
            // if valid prefix exists, the first index
            // is something that can be compared to
            char ch = strs[0].charAt(i);
            // comparing with the other indices
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].charAt(i) != ch || i >= strs[j].length())
                    return strs[j].substring(0, i);
            }//from   w  w  w  . jav a 2  s.c om
        }
        return strs[0].substring(0, minLen);
    }
}

Related

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