Leet Code OJ 14. 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 pre = strs[0];
    int i = 1;
    while(i < strs.length){
        while(strs[i].indexOf(pre) != 0)
            pre = pre.substring(0,pre.length()-1);
        i++;
    }
    return pre;
}

这里的思路是:
首先求2个的最长公共长缀,再用这个长缀去求第3个的最长公共长缀….

你可能感兴趣的:(LeetCode)