Longest Common Prefix

LeetCode.14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

Example:

Input: strs = ["flower","flow","flight"]
Output: "fl"

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

First Solution

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";
    String res = strs[0];
    int i = 1;
    while (i < strs.length) {
        while (strs[i].indexOf(res) != 0) {
            res = res.substring(0, res.length() - 1);
        }
        i += 1;
    }
    return res;
}

Better Solution