• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于java:LeetCode014最长公共前缀

java 搞代码 4年前 (2022-01-28) 24次浏览 已收录 0个评论

最长公共前缀

题目形容:编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例阐明请见LeetCode官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:字符数组法

把第一个字符串放到字符数组chars中,从第二个字符串开始,挨个字符遍历比来源gao@!dai!ma.com搞$$代^@码网拟,失去每次不相等的索引地位p,如果p-1小于0,则示意没有公共前缀;遍历前面的字符串,反复这一过程。 两头只有p-1小于0,间接返回空字符串,没有公共前缀。 遍历完结后,获取chars数组中从0到p-1地位的字符,返回即为最长公共前缀。

<code class="java">public class Solution {
    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0 || strs[0] == null || strs[0].length() == 0) {
            return "";
        }
        char[] chars = strs[0].toCharArray();
        int maxIndex = strs[0].length() - 1;
        for (int i = 1; i < strs.length && maxIndex >= 0; i++) {
            String curStr = strs[i];
            if (curStr == null || curStr.length() == 0) {
                return "";
            }
            int curMax = maxIndex;
            for (int j = 0; j < curStr.length() && j <= curMax && maxIndex >= 0; j++) {
                if (curStr.charAt(j) != chars[j]) {
                    maxIndex = j - 1;
                    break;
                } else {
                    maxIndex = j;
                }
            }
        }
        if (maxIndex < 0) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i <= maxIndex; i++) {
            result.append(chars[i]);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(longestCommonPrefix(new String[]{"ab", "a"}));
    }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于java:LeetCode014最长公共前缀
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址