LeetCode--14

14. 最长公共前缀

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

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

示例 1:

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

示例 2:

复制代码
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

直接上代码:

复制代码
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(!strs.size())
        {
            return "";
        }
        int length=strs[0].size();
        int count = strs.size();
        for(int i=0;i<length;i++)
        {
            char c=strs[0][i];
            for(int j=1;j<count;j++)
            {
                if(i==strs[j].size()||strs[j][i]!=c)
                {
                    return strs[0].substr(0,i);
                }
            }
        }
        return strs[0];

    }
};
相关推荐
hrrrrb11 小时前
【Spring Boot】Spring Boot 中常见的加密方案
java·spring boot·后端
十碗饭吃不饱11 小时前
sql报错:java.sql.SQLSyntaxErrorException: Unknown column ‘as0‘ in ‘where clause‘
java·数据库·sql
饼干吖11 小时前
记一次滑动数组解题
java·算法
ss27311 小时前
手写MyBatis第96弹:异常断点精准捕获MyBatis深层BUG
java·开发语言·bug·mybatis
小马爱打代码11 小时前
分布式锁:原理算法和使用建议
分布式·算法
程序定小飞12 小时前
基于springboot的在线商城系统设计与开发
java·数据库·vue.js·spring boot·后端
uhakadotcom12 小时前
NVIDIA CUDA Python 常用 API 及详细教程
算法·面试·github
LL_break12 小时前
Mysql数据库
java·数据库·mysql
白水先森12 小时前
Python 运算符与列表(list)
java·开发语言
野犬寒鸦12 小时前
从零起步学习Redis || 第十一章:主从切换时的哨兵机制如何实现及项目实战
java·服务器·数据库·redis·后端·缓存