Longest Common Prefix

★☆☆☆☆

Write a function to find the longest common prefix string amongst an array of strings.

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";
    String first = strs[0];
    for (int j = 0; j < first.length(); ++j) {
        for (int i = 1; i < strs.length; ++i) {
            if (j > strs[i].length() - 1 || strs[i].charAt(j) != first.charAt(j))
                return first.substring(0, j);
        }
    }
    return first;
}

results matching ""

    No results matching ""