Java Array Common Prefix longestCommonPrefix(String... strs)

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

Description

Returns the longest common prefix of a group of strings.

License

Open Source License

Parameter

Parameter Description
strs the strings

Return

the longest common prefix

Declaration

private static String longestCommonPrefix(String... strs) 

Method Source Code

//package com.java2s;
/*/*  w  ww.jav  a2s  .c o  m*/
 * Black Duck Software Suite SDK
 * Copyright (C) 2015  Black Duck Software, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

public class Main {
    /**
     * Returns the longest common prefix of a group of strings.
     *
     * <p>
     * Returns an empty string if there are no input strings.
     * </p>
     *
     * @param strs
     *            the strings
     * @return the longest common prefix
     */
    private static String longestCommonPrefix(String... strs) {
        if (strs.length == 0) {
            return "";
        }

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

        int end = 0;

        charLoop: do {
            char c = strs[0].charAt(end);

            for (int i = 1; i < strs.length; i++) {
                if ((strs[i].length() <= end) || (strs[i].charAt(end) != c)) {
                    break charLoop;
                }
            }

            end++;
        } while (true);

        return strs[0].substring(0, end);
    }
}

Related

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