【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 <= strs[i].length <= 200

strs[i] 仅由小写英文字母组成

题解

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];
    }
相关推荐
一起努力啊~3 小时前
算法刷题--哈希表
算法·面试·散列表
willingli3 小时前
c语言经典100题 61-70题
c语言·开发语言·算法
我是小疯子663 小时前
深入解析C++右值引用与移动语义
java·开发语言·算法
踩坑记录3 小时前
leetcode hot100 56.合并区间 medium
leetcode
源代码•宸3 小时前
Golang原理剖析(Map 源码梳理)
经验分享·后端·算法·leetcode·golang·map
程序员-King.3 小时前
day132—链表—K个一组翻转链表(LeetCode-25)
leetcode·链表·贪心算法
Narrastory4 小时前
手把手实现蚁群算法:从数学原理到代码实践
算法
mit6.8244 小时前
八皇后变题hash|网格dp
算法
bybitq4 小时前
LeetCode-437-路径总和3
算法
鱼跃鹰飞4 小时前
Leetcode尊享面试100题:1060. 有序数组中的缺失元素
算法·leetcode·面试