avatar

day18_14_最长公共前缀

题目

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

1
2
输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

1
2
3
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z

Related Topics

  • 字符串

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0){
return "";
}
String res = strs[0];
for(String s: strs){
while (s.indexOf(res) != 0){
res = res.substring(0,res.length()-1);
if(res.isEmpty()){
return "";
}
}
}
return res;

}
}

//runtime:0 ms
//memory:37.7 MB
文章作者: 无知的小狼
文章链接: https://bytedance.press/2020/05/12/20200501/day18_14_%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1%E5%89%8D%E7%BC%80/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 无知的小狼

评论