【LeetCode】14. Longest Common Prefix - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84197016

1. 题目描述:

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 1:

Input: [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:

Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

Note:
All given inputs are in lowercase letters a-z.

2. 思路分析:

题目的意思是给定一个字符串数组,找到数组中所有字符串最长的公共前缀。

最简单的思路就是将str[0],当作当前最长公共前缀,然后依次遍历后续的字符串,如果含有当前公共前缀,则继续遍历;如果不含当前公共前缀,则将当前公共前缀去掉最后一个字符,再继续比较;最后剩下的当前公共前缀即是所有字符串的公共前缀。

3. Java代码:

源代码见我GiHub主页

代码:

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

    String curPrefix = strs[0];
    for (int i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(curPrefix) != 0) {
            curPrefix = curPrefix.substring(0, curPrefix.length() - 1);
            if (curPrefix.isEmpty()) {
                return "";
            }
        }
    }
    return curPrefix;
}

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84197016