【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];
    }
相关推荐
m0_743849652 小时前
LeetCode1732.找到最高海拔
开发语言·python·leetcode
攻城狮7号3 小时前
【3.5】贪心算法-解优势洗牌(类田忌赛马问题)
c++·算法·贪心算法
苦学数据结构6 小时前
25版王道数据结构课后习题详细分析 第五章 树与二叉树 5.3 二叉树的遍历和线索二叉树 选择题部分
数据结构·考研·算法
心.c8 小时前
【数据结构】二叉树基础(带你详细了解二叉树)
数据结构·c++·算法
l9390355488 小时前
【JS】启动多任务排序(200) |思路参考+代码解析+课程表+有向图(C++)
数据结构·c++·算法
多思考少编码8 小时前
Codeforces Round 969 (Div. 2) 题ABC详细题解,包含(C++,Python语言描述)
c++·python·算法·codeforces·算法竞赛
冰暮流星9 小时前
动态规划法例题
算法·动态规划
桃酥4039 小时前
算法day17|如何求普通二叉树的众数
数据结构·c++·算法·leetcode·哈希算法
DelTTAA9 小时前
【LeetCode】刷题记录--单链表相关
算法·leetcode·职场和发展
秋风战士10 小时前
通信算法之230: 5G随机接入PRACH及长度计算
网络·经验分享·算法