Leetcode 题目解析之 Longest Common Prefix

2022-02-13 15:22:14 浏览数 (1)

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

代码语言:javascript复制
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        if (strs.length == 1) {
            return strs[0];
        }
        String string = strs[0];
        for (int i = 0; i < string.length(); i  ) {
            for (int j = 1; j < strs.length; j  ) {
                if (!(i < strs[j].length() && string.charAt(i) == strs[j]
                        .charAt(i))) {
                    return string.substring(0, i);
                }
            }
        }
        return string;
    }

0 人点赞