当前位置:网站首页>【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;
}
}

边栏推荐
- Gbase8s database select has order by Clause 1
- iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务
- Is it safe for Orient Fortune Securities to open an account? Handling of securities account opening
- 服务数百万开发者,首届 Techo Day 腾讯技术开放日发布 7 款“轻量级”产品
- 力扣每日一题-第31天-1779.找到最近的有相同x或y坐标的点
- 杰理之WiFi干扰蓝牙【篇】
- GBase8s数据库INTO EXTERNAL 子句
- MySQL数据库主从同步,一致性解决方案
- GBase8s数据库select有HAVING 子句
- How to obtain method parameter values through WinDbg
猜你喜欢
![[pbootcms template] composition website / document download website source code](/img/6e/51bbb4ce961defa4abd098ff3af21f.jpg)
[pbootcms template] composition website / document download website source code

Pro test! Centos7 deploy PHP + spool
![Jerry's about TWS channel configuration [chapter]](/img/2c/58a49dea7a7931c4d1f055548c2493.png)
Jerry's about TWS channel configuration [chapter]

& 4 express framework

亲测!Centos7部署PHP + Swoole

参加2022年杭州站Cocos Star Meetings

&4 express框架

& 3 view request message and response message in browser

大家有没有觉得学机械的人很可怕?

百度云盘不限速下载大文件(2021-11亲测有效)
随机推荐
Jerry's about TWS pairing mode configuration [chapter]
Wang Yingqi, founder of ones, talks to fortune (Chinese version): is there any excellent software in China?
Wonderful! Miaoying technology fully implements Zadig to help container construction, and fully embraces kubernetes and Yunyuan
Weekly recommended short video: How did Einstein think?
联想领像 lenovoimage 部分打印机 驱动 PPD 文件
GBase8s数据库select有ORDER BY 子句4
Ttchat x Zadig open source co creates helm access scenarios, and environmental governance can be done!
[pbootcms template] composition website / document download website source code
内插散点数据
When a technician becomes a CEO, what "bugs" should be modified?
GBase 8s 扩展外连接1
杰理之发起对耳配对、回连、开启可发现、可连接的轮循函数【篇】
力扣每日一题-第31天-1779.找到最近的有相同x或y坐标的点
龙书虎书鲸书啃不动?试试豆瓣评分9.5的猴书
Codeforces Round #803 (Div. 2)
Installation and configuration of MariaDB
Gbase 8s extended external connection 1
杰理之关于 TWS 交叉配对的配置【篇】
杰理之WiFi干扰蓝牙【篇】
Gbase8s database select has a having clause