LeetCode 最长公共前缀(探索字节跳动)
2024-10-06 20:05:12
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 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);
}
};
最新文章
- ArcGIS Desktop 遇到严重的应用程序错误
- javascript 倒计时获取验证码
- C# 微信扫码支付 回调页面
- hdu 4642 Fliping game(博弈)
- 关于SQL Server 2005 的自动远程数据库备份
- Bill Total Value
- vim 正则非贪婪模式
- Myschool乱码问题 和mysql 备份还原
- OO课程中IDEA相关插件的使用
- springboot寻找property的顺序
- Windows下jupyter notebook 修改打开的浏览器
- win10安装PS和AI后报代码为16的错误解决方法
- PHP5.4 需要添加的configure参数
- vs2012
- forward与redirect
- aiohttp爬虫的模板,类的形式
- obtainBuffer timed out (is the CPU pegged?)
- springboot shiro没有注解解决方案
- 将td中文字过长的部分变成省略号显示的小技巧
- mac manpages 汉化