力扣--最长公共前缀

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

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

示例 1:

复制代码
输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

复制代码
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
复制代码
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs)
    {
        if(strs.size()==0)
        {
            return "";
        }
        int len=strs[0].size();
        int count=strs.size();
        for(int i=0;i<len;++i)
        {
            char ch=strs[0][i];
            for(int j=1;j<count;++j)
            {
                if(i==strs[j].size()||ch!=strs[j][i])//i到达strs[j]的边界或者出现字符不相等
                {
                    return strs[0].substr(0,i);
                }
            }
        }
        return strs[0];
    }
};
相关推荐
Lips61119 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
代码村新手19 小时前
C++-类和对象(中)
java·开发语言·c++
今天_也很困20 小时前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
Ccjf酷儿20 小时前
C++语言程序设计 (郑莉)第十章 泛型程序设计与C++标准模板库
开发语言·c++
千金裘换酒21 小时前
LeetCode 数组经典题刷题
算法·leetcode·职场和发展
alphaTao1 天前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo1 天前
leetcode 2943
数据结构·算法·leetcode
明洞日记1 天前
【CUDA手册002】CUDA 基础执行模型:写出第一个正确的 Kernel
c++·图像处理·算法·ai·图形渲染·gpu·cuda
程序员-King.1 天前
day134—快慢指针—环形链表(LeetCode-141)
算法·leetcode·链表·快慢指针
Swift社区1 天前
LeetCode 376 摆动序列
算法·leetcode·职场和发展