力扣--最长公共前缀

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

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

示例 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];
    }
};
相关推荐
·present·1 小时前
CSAPP(lecture 3)
c++
别动我齐刘海1 小时前
机器人 C++ / 系统联调补强2——异常处理、Protobuf
linux·c++·人工智能·学习·算法·机器学习·机器人
basketball6162 小时前
C++ 中字符串与常见类型的转换总结
开发语言·c++
文丑颜不良啊2 小时前
LeetCode276~300题目解析
java·leetcode
等我调个Bug2 小时前
C++智能指针通俗讲解
开发语言·c++
kyle~4 小时前
时间同步 --- PTP 与 Scheduled Action Command
c++·数码相机·机器人·传感器
傅科摆 _ py4 小时前
链表力扣复习
数据结构·leetcode·链表
syagain_zsx6 小时前
WebSocket 教程:websocketpp 写 echo 服务端
linux·网络·c++·websocket·网络协议·工具库
大陈子编程6 小时前
C++ CSP-J 与 CSP-S 题单:洛谷 140 题知识点全覆盖
c++