14. Longest Common Prefix (最长公共前缀)

Posted

tags:

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

一、Description:

  Write a function to find the longest common prefix string amongst an array of strings.

    

public class Solution {
    public String longestCommonPrefix(String[] strs) {

    }
}

 

二、Solutions:

  1、思路:

    开始想的是数组中每两个相邻字符串进行比较,并取比较的最短的前缀作为整个数组的最短前缀。时间复杂度为 n^2

  

public static String longestCommonPrefix(String[] strs) {

        if(strs.length == 0) return "";

        int len  , commonLen = strs[0].length();
        for (int i = 0; i <  strs.length - 1; i++) {
           len = getCommonPrefix(strs[i], strs[i+1]);
           if(commonLen > len) commonLen = len;
        }

        return strs[0].substring(0, commonLen);
    }

    private static int getCommonPrefix(String str1, String str2) {
        int result = 0;
        for (int i = 0; i < str1.length() && i < str2.length(); i++) {
            if(str1.charAt(i) == str2.charAt(i))
                result++;
            else
                break;
        }
        return result;
    }

  2、优化:

    以第一个字符串作为公共前缀prefix,依次作为第2个字符串的前缀进行比较,若不符合,则prefix长度-1.. ;符合则再与第3个字符串进行比较...时间复杂度m*n

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

 

    

以上是关于14. Longest Common Prefix (最长公共前缀)的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 14. Longest Common Prefix

leet_14 Longest Common Prefix

14Longest Common Prefix

14. Longest Common Prefix

Leetcode 14. Longest Common Prefix

14. Longest Common Prefix