力扣--最长公共前缀

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

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

示例 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];
    }
};
相关推荐
MC皮蛋侠客21 小时前
Google Test 单元测试指南
c++·单元测试·google test
艾莉丝努力练剑1 天前
【Linux:文件】Ext系列文件系统进阶
linux·运维·服务器·c++·文件系统·文件io·ext
basketball6161 天前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
Fre丸子_1 天前
自定义文件夹选取功能
c++
思麟呀1 天前
C++工业级日志项目(六)异步日志器
linux·c++·windows
PAK向日葵1 天前
从零实现 Python 虚拟机(二):S.A.A.U.S.O 的总体架构设计
c++·python
无限进步_1 天前
【C++】weak_ptr、循环引用与线程安全
开发语言·数据结构·c++·算法·安全
罗超驿1 天前
9.LeetCode 209. 长度最小的子数组 | 滑动窗口专题详解
java·算法·leetcode·面试
水蓝烟雨1 天前
0135. 分发糖果
算法·leetcode
咩咦1 天前
C++学习笔记30:友元类、内部类和封装
c++·学习笔记·类和对象·封装·内部类·友元类·friend