java [14。最长的共同前缀] #Array #Leetcode #Easy

Posted

tags:

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

public class Solution {
    /*
    *
    * 14. Longest Common Prefix
    * Write a function to find the longest common prefix string amongst an array of strings.
    * My stupid solution with O(n^2) Complexity.
    *
    * */

    public  String longestCommonPrefix(String[] strs) {

        if(strs == null || strs.length == 0)
            return "";
        String start = strs[0];
        for(int i = 1; i <= start.length(); i++){
            for(String s: strs){
                if(s.length() < i || !s.substring(0,i).equals(start.substring(0,i))){
                    return start.substring(0,i-1);
                }
            }
        }
        return start;
    }
}

    /*
    *  method 2:
    *  want the longest 
    *  choose the first string  in the array
    *  and shrink it until to the end
    * */
    public static String longestCommonPrefix2(String[] strs) {
        // corner case
        if(strs == null || strs.length == 0)
            return "";

        String prefix = strs[0];

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

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

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

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

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

java 最长的共同前缀

JSLeetCode14. 最长公共前缀

java 14.最长公共前缀(#1排序).java