java 最长的共同前缀

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 最长的共同前缀相关的知识,希望对你有一定的参考价值。

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

        String common = strs[0];
        for (int i = 1; i < strs.length; i++) {

            common = sharedPrefix(common, strs[i]);

            if (common.length() == 0) break;
        }

        return common;
    }

    // Helper for longestCommonPrefix
    public String sharedPrefix(String currentPrefix, String string) {

        if (currentPrefix == null || string == null) return "";

        // If we contain the current prefix then go with it. 
        // Otherwise we need to work backwards and figure it out.
        if (string.startsWith(currentPrefix)) {
            return currentPrefix;
        }

        String matchingSubrange = "";
        for (int i = 0; i < currentPrefix.length() && i < string.length(); i++) {

            String subrange = currentPrefix.substring(0, i + 1);
            if (string.startsWith(subrange)) {
                matchingSubrange = subrange;
            } else {
                return matchingSubrange;
            }
        }

        return matchingSubrange;
    }

以上是关于java 最长的共同前缀的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 14.最长的共同前缀 - 难度容易 - 2018.8.20

[LeetCode] 14. Longest Common Prefix 最长共同前缀

[LeetCode] 14. Longest Common Prefix 最长共同前缀

LeetCode9.Array and String — Longest Common Prefix 最长共同前缀

JSLeetCode14. 最长公共前缀

java 最长公共字符串前缀 - 最长公共前缀