算法-leetcode-每日一题-最长前缀

Example 1:
Input: [“flower”,“flow”,“flight”]
Output: “fl”
Example 2:
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

分析:本题直接上代码,看代码更清晰。

public static String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";

    String prefix = strs[0];     //用第一个字符串作为前缀
    int currentIndex = 0;        //当前字符串索引
    while (currentIndex < strs.length) {//循环每个字符串
        //该方法的重点在于只要当前的字符串满足了一个前缀,则不管这个前缀后面怎么被截取都能满足,这样就值需要保证一次循环遍历
        while (!strs[currentIndex].startsWith(prefix)) {//如果当前字符串不是以这个为前缀
            prefix = prefix.substring(0, prefix.length() - 1);//则截取当前前缀的前面部分,直到满足为止
            if (prefix.isEmpty()) {
                return "";
            }
        }
        //满足了就搜索下一个字符串,让其也满足
        currentIndex++;
    }
    return prefix;
}

猜你喜欢

转载自blog.csdn.net/wujingchangye/article/details/88542130