当前位置:网站首页>【LeetCode】14、最长公共前缀
【LeetCode】14、最长公共前缀
2022-06-29 11:35:00 【小曲同学呀】
14、最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
解题思路:
此题难度并不难,就用最通俗的解法,数组内的字符串一一比较,相同的取出来,不同的pass掉即可。
- 标签:链表
- 当字符串数组长度为 0 时则公共前缀为空,直接返回
- 令最长公共前缀 ans 的值为第一个字符串,进行初始化
- 遍历后面的字符串,依次将其与 ans 进行比较,两两找出公共前缀,最终结果即为最长公共前缀
- 如果查找过程中出现了 ans 为空的情况,则公共前缀不存在直接返回
- 时间复杂度:O(s)O(s),s 为所有字符串的长度之和
参考代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String ans = strs[0];
for(int i =1;i<strs.length;i++) {
int j=0;
for(;j<ans.length() && j < strs[i].length();j++) {
if(ans.charAt(j) != strs[i].charAt(j))
break;
}
ans = ans.substring(0, j);
if(ans.equals(""))
return ans;
}
return ans;
}
}

边栏推荐
- Dragon Book tiger Book whale Book gnawing? Try the monkey book with Douban score of 9.5
- Unified exception reporting practice based on bytecode
- GBase8s数据库select有ORDER BY 子句4
- 地球观测卫星数据
- 《高难度谈话》突破谈话瓶颈,实现完美沟通
- Helping the ultimate experience, best practice of volcano engine edge computing
- Gbase8s database select has order by Clause 4
- How to view saved passwords of websites
- Jerry's initiation of ear pairing, reconnection, and opening of discoverable and connectable cycle functions [chapter]
- Li Kou daily question - day 31 -1779 Find the nearest point with the same X or Y coordinate
猜你喜欢
随机推荐
Gbase8s database select has order by Clause 4
Easy express: we use Zadig to realize 10000 times of construction and deployment, smart operation and maintenance, and release development productivity
GBase8s数据库select有ORDER BY 子句6
Go高级工程师必修课 | 真心建议你来听听,别错过~
&4 express框架
Is the table queried by this EMR sparksql node ODPs?
An interpretable geometric depth learning model for structure based protein binding site prediction
GBase8s数据库select有ORDER BY 子句5
MySQL数据库主从同步,一致性解决方案
联想领像 lenovoimage 部分打印机 驱动 PPD 文件
Jerry's WiFi interferes with Bluetooth [chapter]
JVM之方法区
内插散点数据
当技术人成长为 CEO,应该修改哪些“Bug”?
MIT线性代数中文笔记
Ttchat x Zadig open source co creates helm access scenarios, and environmental governance can be done!
What are outer chain and inner chain?
ERP编制物料清单 基础
MariaDB的安装与配置
东方财富证券开户安全吗 证券开户办理





![[VTK] MFC grid editor based on vtk8.2](/img/c5/d0f070ccb819fc682855319b7415e0.png)



