Skip to content

Commit 261e140

Browse files
authored
Add files via upload
1 parent cd11cb2 commit 261e140

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

14.最长公共前缀.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# 14.最长公共前缀
2+
3+
编写一个函数来查找字符串数组中的最长公共前缀。
4+
5+
如果不存在公共前缀,返回空字符串 ""。
6+
7+
8+
9+
示例 1:
10+
11+
```
12+
输入:strs = ["flower","flow","flight"]
13+
输出:"fl"
14+
```
15+
16+
17+
示例 2:
18+
19+
```
20+
输入:strs = ["dog","racecar","car"]
21+
输出:""
22+
解释:输入不存在公共前缀。
23+
```
24+
25+
26+
提示:
27+
28+
1 <= strs.length <= 200
29+
0 <= strs[i].length <= 200
30+
strs[i] 仅由小写英文字母组成
31+
32+
来源:力扣(LeetCode)
33+
链接:https://leetcode-cn.com/problems/longest-common-prefix
34+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
35+
36+
java实现:
37+
38+
```java
39+
class Solution {
40+
public String longestCommonPrefix(String[] strs) {
41+
if((strs==null)||strs.length==0){
42+
return "";
43+
}
44+
String prefix = strs[0];
45+
for(int i = 1;i<strs.length;i++){
46+
prefix = lCP(prefix,strs[i]);
47+
if(prefix.length()==0)break;
48+
}
49+
return prefix;
50+
}
51+
public String lCP(String str1,String str2){
52+
int len = Math.min(str1.length(),str2.length());
53+
int index = 0;
54+
while((index<len)&&str1.charAt(index)==str2.charAt(index)){
55+
index++;
56+
}
57+
return str1.substring(0,index);
58+
}
59+
}
60+
```
61+

0 commit comments

Comments
 (0)