【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];
    }
相关推荐
super杨某人1 分钟前
算法十日谈:双指针
数据结构·算法
kklovecode3 分钟前
C语言数组:零长数组,可变数组,多维数组
java·c语言·算法
0***m8225 分钟前
MATLAB高效算法实战技术文章大纲向量化运算替代循环结构
开发语言·算法·matlab
AY呀6 分钟前
《从赛车到代码:我是如何理解深度优先搜索的》
算法
不知名XL8 分钟前
day22 回溯算法part04
算法·leetcode·职场和发展
夏鹏今天学习了吗13 分钟前
【LeetCode热题100(77/100)】杨辉三角
算法·leetcode·职场和发展
1***438014 分钟前
MATLAB高效算法实战技术文章大纲工程领域的应用背景
开发语言·算法·matlab
求梦82015 分钟前
【力扣hot100题】搜索二维矩阵II(16)
算法·leetcode·矩阵
2501_9011478326 分钟前
单词拆分(Word Break)题解 | 动态规划解法
考研·算法·动态规划
翱翔的苍鹰41 分钟前
使用PyTorch实现线性回归的完整流程
算法·回归·线性回归