java最长公共前缀

leetcode学习

题目链接: https://leetcode-cn.com/problems/longest-common-prefix/

public String longestCommonPrefix(String[] strs) {
     
        String result = "";
        int index = 1;
        out:
        while (true) {
     
            if (strs.length==0){
     
                break out;
            }
            if (strs[0].length() == 0 || strs[0].length() < index) {
     
                break out;
            }
            String substring = strs[0].substring(0, index);
            for (String str : strs) {
     
                if (!str.startsWith(substring)){
     
                    break out;
                }
            }
            result = substring;
            index++;
        }
        return result;
    }
取数组首个字符串,取第一位字符逐位与数组内其它字符串比较前缀,若全部相同,则前缀多取一位,直至出现不同的为止。

你可能感兴趣的:(java,算法,java,leetcode,算法)