Java Array Common Prefix longestCommonPrefix(String[] strs)

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

Description

longest Common Prefix

License

Apache License

Declaration

public static String longestCommonPrefix(String[] strs) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }//from   w w  w . j a  v a 2s .  c  om

        if (strs.length == 1) {
            return strs[0];
        }

        StringBuilder prefix = new StringBuilder();
        int idx = 0;
        while (true) {

            if (idx >= strs[0].length()) {
                return prefix.toString();
            }

            char c = strs[0].charAt(idx);
            boolean match = true;
            for (int i = 1; i < strs.length; i++) {
                if (strs[i] == null || idx >= strs[i].length()) {
                    return prefix.toString();
                }
                if (strs[i].charAt(idx) != c) {
                    match = false;
                    break;
                }
            }

            if (match) {
                prefix.append(c);
                idx++;
            } else {
                return prefix.toString();
            }
        }
    }
}

Related

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