Java Array Common Prefix longestCommonPrefix(String str1, String str2)

Here you can find the source of longestCommonPrefix(String str1, String str2)

Description

longest Common Prefix

License

Apache License

Declaration

public static String longestCommonPrefix(String str1, String str2) 

Method Source Code

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

public class Main {
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 1) {
            return strs[0];
        }//ww  w .j  a  v  a2 s .  com
        String str = longestCommonPrefix(strs[0], strs[1]);
        int i = 2;
        while (i < strs.length) {
            str = longestCommonPrefix(str, strs[i]);
            i++;
        }

        return str;
    }

    public static String longestCommonPrefix(String str1, String str2) {
        int i = 0;
        while (i < str1.length() && i < str2.length() && str1.charAt(i) == str2.charAt(i)) {
            i++;
        }
        String str = str1.substring(0, i);
        return str;
    }
}

Related

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