个人记录-LeetCode 14. Longest Common Prefix

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

问题要求是:
找出一个字符串数组中,所有字符串共有的最长前缀子串。

代码示例:
1、暴力解法
以第一个字符串为基准,其它字符串均与其进行比较,找出最长的子串。

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null) {
            return null;
        }

        //the num of all strings
        int strNum = strs.length;

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

        if (strNum == 1) {
            return  strs[0];
        }

        //the min len of a string
        int minLen = strs[0].length();
        for (int i = 1; i < strNum; ++i) {
            if (strs[i].length() < minLen) {
                minLen = strs[i].length();
            }
        }

        //use strs[0] as standard
        int commLen = 0;
        boolean allEqual = true;
        for (int i = 0; i < minLen; ++i) {
            for (int j = 1; j < strNum; ++j) {
                if (strs[j].charAt(i) != strs[0].charAt(i)) {
                    allEqual = false;
                    break;
                }
            }

            if (allEqual) {
                ++commLen;
            } else {
                break;
            }
        }

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

2、利用Arrays的sort功能

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

        if (strs.length == 1) {
            return strs[0];
        }

        //排序之中也有不同字符串的比较,但系统库的比较方式更快
        Arrays.sort(strs);
        char[] first = strs[0].toCharArray();
        char[] last = strs[strs.length-1].toCharArray();

        for(int i=0; i<first.length; i++){
            if(first[i]!=last[i]) return strs[0].substring(0,i);
        }
        return strs[0];
    }
}

你可能感兴趣的:(个人记录-LeetCode 14. Longest Common Prefix)