Skip to content

Commit 88a972d

Browse files
authored
Create 014. Longest Common Prefix.java
1 parent 99ad339 commit 88a972d

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

014. Longest Common Prefix.java

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// https://leetcode.com/problems/longest-common-prefix
2+
public class Solution {
3+
public String longestCommonPrefix(String[] strs) {
4+
if (strs.length == 0) return "";
5+
else if (strs.length == 1) return strs[0];
6+
else {
7+
Arrays.sort(strs);
8+
9+
String prefix = "";
10+
for (int i = 0; i < strs[0].length(); i++) {
11+
prefix = strs[0].substring(0, i+1);
12+
System.out.println(prefix);
13+
for (int s = 0; s < strs.length; s++) {
14+
if (!prefix.equals(strs[s].substring(0, i+1))) {
15+
return prefix.substring(0, prefix.length() - 1);
16+
}
17+
}
18+
}
19+
20+
return prefix;
21+
}
22+
}
23+
}
24+
25+
// reference
26+
// https://discuss.leetcode.com/topic/6987/java-code-with-13-lines
27+
28+
public String longestCommonPrefix(String[] strs) {
29+
if(strs == null || strs.length == 0) return "";
30+
String pre = strs[0];
31+
int i = 1;
32+
while(i < strs.length){
33+
while(strs[i].indexOf(pre) != 0)
34+
pre = pre.substring(0,pre.length()-1);
35+
i++;
36+
}
37+
return pre;
38+
}

0 commit comments

Comments
 (0)