算法每日一题20190623:最长公共前缀
算法 大约 979 字题目
难易程度:【简单】
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
博主答案
执行用时 :7 ms
, 在所有Java
提交中击败了33.34%
的用户
内存消耗 :35.7 MB
, 在所有Java
提交中击败了89.06%
的用户
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String first = strs[0];
int index = 0;
String prefix = "";
A:
while (index < first.length()) {
prefix = first.substring(0, index + 1);
for (int i = 1; i < strs.length; i++) {
if (!strs[i].startsWith(prefix)) {
prefix = first.substring(0, index);
break A;
}
}
index++;
}
return prefix;
}
}
官方答案
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
阅读 2329 · 发布于 2019-06-23
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
MySQL 最后一次查询花费时间阅读 1952
-
Spring Boot logback 导致 /tmp 磁盘爆满阅读 3363
-
软考-系统架构设计师:进程管理 - PV 操作阅读 4346
-
JavaScript onstorage 监听本地存储变更事件阅读 2010
-
Linux Shell 脚本监控进程状态阅读 4148
-
Android ListView 添加头布局阅读 2305
-
Windows WSL 下 Docker 启动报 waiting for init preliminary setup caused: EOF: unknown 错误阅读 2845
-
Go 预定义标识符阅读 2232
-
Kubernetes 数据存储 PV 和 PVC阅读 860
-
PostgreSQL update from 根据 A 表更新 B 表阅读 2948