力扣--最长公共前缀

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

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

示例 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];
    }
};
相关推荐
所以遗憾是什么呢?6 小时前
【题解】Educational Codeforces Round 195 (Rated for Div. 2) ABCDE
c++·动态规划·acm·icpc·ccpc·xcpc·codeforecs
Lhan.zzZ8 小时前
Qt WebEngineView 在 Linux 上无法加载网页:从“看不见 HTML“到“禁用沙箱“
linux·c++·qt
sysu_chenxy10 小时前
二重循环输出二维图形
c++
Navigator_Z10 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil20810 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil20811 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
划破黑暗的第一缕曙光11 小时前
[C++]:2.类和对象(下)
c++·类和对象·对象·类
Nil20811 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
黎相思12 小时前
LRU Cache
c++·缓存
UIU11412 小时前
P1003 [NOIP 2011 提高组] 铺地毯
数据结构·c++·算法