【Leetcode】14. 最长公共前缀

leetcode原地址:https://leetcode.cn/problems/longest-common-prefix

描述

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

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

示例 1:

输入:strs = "flower","flow","flight"

输出:"fl"

示例 2:

输入:strs = "dog","racecar","car"

输出:""

解释:输入不存在公共前缀。

提示:

1 <= strs.length <= 200

0 <= strsi.length <= 200

strsi 仅由小写英文字母组成

题解

java 复制代码
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int length = strs[0].length();
        int count = strs.length;
        for (int i = 0; i < length; i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < count; j++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }
        return strs[0];
    }
相关推荐
_Narcissus_34 分钟前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.1 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks1 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路1 小时前
算法8.环形队列
算法
O。O蛋黄酥啊2 小时前
GraphRAG 和 LightRAG 详解与对比
人工智能·python·算法·rag·graphrag·lightrag
Σίσυφος19002 小时前
depth_from_focus 详解
算法
圣保罗的大教堂2 小时前
leetcode 2996. 大于等于顺序前缀和的最小缺失整数 简单
leetcode
疯狂打码的少年2 小时前
【数据结构】八大排序算法对比总结(时间/空间/稳定性)
数据结构·笔记·算法
树獭哥2 小时前
量化金融入门:从数据规则到随机游走与凯利公式
人工智能·算法·金融·量化金融
圣保罗的大教堂2 小时前
leetcode 3702. 按位异或非零的最长子序列 中等
leetcode