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

        int i = 0;
        String prefix = "";
        String result = "";
        boolean broken = false;
        while (true) {
            i++;/*w w w.j  a v a  2s. co  m*/
            result = prefix;
            if (i > strs[0].length())
                break;//this will break out the while loop
            prefix = strs[0].substring(0, i);
            for (String word : strs) {
                if (i > word.length() || !word.startsWith(prefix)) {
                    broken = true;
                    break;//this will only break out of the for loop
                }
            }
            if (broken)
                break;//this will break out the while loop
        }
        return result;
    }
}

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, int l, int r)
  7. longestCommonPrefix1(String[] strs)
  8. longestCommonPrefix2(String[] strs)
  9. longestCommonPrefix3(String[] strs)