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) {
        String str = "";
        if (strs.length == 0)
            return str;
        if (strs.length == 1)
            return strs[0];
        for (int i = 1; i < strs.length; i++) {
            if (i == 1) {
                int n = strs[0].length() > strs[1].length() ? strs[1]
                        .length() : strs[0].length();
                for (int j = 0; j < n; j++) {
                    if (strs[0].charAt(j) == strs[1].charAt(j))
                        str = str + strs[0].charAt(j);
                    else
                        break;
                }/*from  w ww  . ja v a 2 s.  c o  m*/
            } else {
                while (!strs[i].startsWith(str))
                    str = str.substring(0, str.length() - 1);
            }
        }
        return str;
    }
}

Related

  1. longestCommonPrefix(String[] strs)
  2. longestCommonPrefix(String[] strs)
  3. longestCommonPrefix(String[] strs)
  4. longestCommonPrefix(String[] strs)
  5. longestCommonPrefix(String[] strs)
  6. longestCommonPrefix(String[] strs)
  7. longestCommonPrefix(String[] strs, int l, int r)
  8. longestCommonPrefix1(String[] strs)
  9. longestCommonPrefix2(String[] strs)