当前位置:网站首页>LeetCode_14_最长公共前缀
LeetCode_14_最长公共前缀
2022-08-08 10:37:00 【Fitz1318】
题目链接
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
解题思路
- 当字符串数组为空时,直接返回
ans
初始化为第一个字符,遍历后面的字符串,依次与ans
比较,两两找出公共前缀并更新ans
,最终结果即为最长公共前缀- 如果在查找过程中出现了
ans = null
的情况,则说明公共前缀不存在,直接返回
AC代码
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;
for (j = 0; 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 "";
}
}
return ans;
}
}
边栏推荐
猜你喜欢
随机推荐
分布式系统设计策略
在mysql中,存储过程中参数为中文 乱码解决方案
持久化键值数据库的数据是保存在内存中吗?
深度强化学习发展史
机器学习(十六)推荐系统
Solutions and ideas for the problem that Loadrunner's recording event is 0
EZVIZ and Xiaomi compete against smart cameras
How to uniformly handle error exceptions in embedded C programming?
功夫再高也怕菜刀,产品经理的那些事
在SAP分析云里根据业务数据绘制词云(Word Cloud)
为什么说键值数据库有高可扩展性呢?
Machine learning model too slow?Look at Intel (R) extension to accelerate
Optional常用方法解析
go调度原理
Tensorflow basic concepts
典型的NoSQL数据库有哪些呢?
MySQL源码解析之执行计划
使用ApacheBench来对美多商城的秒杀功能进行高并发压力测试
键值数据库中可以对值进行查询嘛?
2G 3G 4G 5G 基站覆盖范围