题目描述

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

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

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

解题思路

以第一个字符串为比较对象,对之后的字符串从第一个字符开始依次比较到当前的最长前缀。

代码

 class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()) return "";
string res = strs[];
int max_len = res.length();
for(string s: strs){
for(int i = ; i < max_len && i < s.length(); i++){
if(res[i] != s[i]){
max_len = i;
break;
}
}
if(max_len > s.length()) max_len = s.length();
if(max_len == ) break;
}
return res.substr(, max_len);
}
};

最新文章

  1. ArcGIS Desktop 遇到严重的应用程序错误
  2. javascript 倒计时获取验证码
  3. C# 微信扫码支付 回调页面
  4. hdu 4642 Fliping game(博弈)
  5. 关于SQL Server 2005 的自动远程数据库备份
  6. Bill Total Value
  7. vim 正则非贪婪模式
  8. Myschool乱码问题 和mysql 备份还原
  9. OO课程中IDEA相关插件的使用
  10. springboot寻找property的顺序
  11. Windows下jupyter notebook 修改打开的浏览器
  12. win10安装PS和AI后报代码为16的错误解决方法
  13. PHP5.4 需要添加的configure参数
  14. vs2012
  15. forward与redirect
  16. aiohttp爬虫的模板,类的形式
  17. obtainBuffer timed out (is the CPU pegged?)
  18. springboot shiro没有注解解决方案
  19. 将td中文字过长的部分变成省略号显示的小技巧
  20. mac manpages 汉化

热门文章

  1. Springboot整合MybatisPlus
  2. Vue-img-preload
  3. PyInstaller使用教程
  4. AD转换 XPT2046
  5. PAT Basic 1063 计算谱半径 (20 分)
  6. [USACO15FEB]Superbull 超级牛
  7. Centos6系统启动流程
  8. linux基础_使用指令2
  9. Java队列与栈转换中String.Valueof()使用
  10. 如何定义搜索面板的过滤器?DevExpress WPF超easy