Here you can find the source of longestCommonPrefix(String[] stringArray)
Parameter | Description |
---|---|
stringArray | an array of strings. |
public static final String longestCommonPrefix(String[] stringArray)
//package com.java2s; // Licensed under the terms of the New BSD License. Please see associated LICENSE file for terms. import java.util.Arrays; import java.util.List; public class Main { /**/*from w w w . j a va 2s. co m*/ * Returns the longest common prefix for the specified strings * * @param s the first string. * @param t the second string. * @return the longest common prefix for the specified strings */ public static final String longestCommonPrefix(String s, String t) { int n = Math.min(s.length(), t.length()); int i; for (i = 0; i < n; ++i) { if (s.charAt(i) != t.charAt(i)) { break; } } return s.substring(0, i); } /** * Returns the longest common prefix for the specified strings. * * @param stringArray an array of strings. * @return the longest common prefix for the specified strings. */ public static final String longestCommonPrefix(String[] stringArray) { return longestCommonPrefix(Arrays.asList(stringArray)); } /** * Returns the longest common prefix for the specified strings. * * @param stringList a list of strings. * @return the longest common prefix for the specified strings. */ public static final String longestCommonPrefix(List<String> stringList) { final int n = stringList.size(); if (n < 1) { throw new IllegalArgumentException(); } String lcpString = stringList.get(0); for (String string : stringList) { lcpString = longestCommonPrefix(lcpString, string); } return lcpString; } }