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

边栏推荐
- How to obtain method parameter values through WinDbg
- 杰理之发起对耳配对、回连、开启可发现、可连接的轮循函数【篇】
- ERP preparation of bill of materials Huaxia
- 百度云盘不限速下载大文件(2021-11亲测有效)
- [pbootcms template] composition website / document download website source code
- Jerry's WiFi interferes with Bluetooth [chapter]
- Jerry's manual pairing method [chapter]
- Codeforces Round #803 (Div. 2)
- Li Kou daily question - day 31 -13 Roman array to integer
- [VTK] MFC grid editor based on vtk8.2
猜你喜欢
Some printer driver PPD files of Lenovo Lingxiang lenovoimage

Embedded database development programming (IV) -- DDL, DML

智能指标驱动的管理和决策平台 Kyligence Zen 全新上线,限量内测中

Jericho's position on initiating the connection back to the opposite ear: 【 chapter 】
![[pbootcms template] composition website / document download website source code](/img/6e/51bbb4ce961defa4abd098ff3af21f.jpg)
[pbootcms template] composition website / document download website source code

保障饮用水安全!番禺沙湾水道水质在线监测系统通过验收

Imile uses Zadig's multi cloud environment to deploy thousands of times a week to continuously deliver global business across clouds and regions

ERP preparation of bill of materials Huaxia

AutoCAD - text display mode and how CAD can directly open Tianzheng drawings

论文复现——AC-FPN:Attention-guided Context Feature Pyramid Network for Object Detection.
随机推荐
ShanDong Multi-University Training #3
杰理之关于 TWS 交叉配对的配置【篇】
535. TinyURL 的加密与解密 : 设计一个 URL 简化系统
Li Kou daily question - day 31 -1779 Find the nearest point with the same X or Y coordinate
MySQL主从同步之 异步复制 半同步复制 全同步复制
GBase8s数据库select有ORDER BY 子句4
杰理之关于 TWS 配对方式配置【篇】
Wonderful! Miaoying technology fully implements Zadig to help container construction, and fully embraces kubernetes and Yunyuan
AUTOCAD——文字显示方式、CAD怎么直接打开天正图纸
RSLO:自监督激光雷达里程计(实时+高精度,ICRA2022)
面试突击61:说一下MySQL事务隔离级别?
这个EMR-SparkSQL节点,他查询的表是不是ODPS的啊?
GBase8s数据库select有ORDER BY 子句1
Numpy's ndarray array Foundation
Li Kou daily question - day 31 -13 Maximum perimeter of triangle
爱可可AI前沿推介(6.29)
MIT线性代数中文笔记
力扣每日一题-第31天-1779.找到最近的有相同x或y坐标的点
在校生的编程故事
嵌入式数据库开发编程(四)——DDL、DML