Java Array Common Prefix longestCommonPrefix(String[] strs)

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

Description

Simple approach to compare first, second, ...

License

Open Source License

Declaration

static String longestCommonPrefix(String[] strs) 

Method Source Code

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

public class Main {
    /**//from ww w .j  a  v a  2 s . c  o m
     * Simple approach to compare first, second, ... elements of every element in array with first element.
     * if any string with not equal character found, return prefix.
     */
    static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0)
            return "";
        if (strs.length == 1)
            return strs[0];

        int len = strs[0].length();
        int i = 0;
        for (; i < len; i++) {

            for (int j = 1; j < strs.length; j++) {
                if (i == strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i))
                    return strs[0].substring(0, i);
            }
        }
        return strs[0].substring(0, i);
    }
}

Related

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