Skip to content

Commit 01b5c8e

Browse files
committed
Add LeetCode 14. Longest Common Prefix java solution
1 parent edfe3cc commit 01b5c8e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public static boolean isCommonForLength(int size, String[] strs) {
3+
String substr = "";
4+
5+
for (String s: strs) {
6+
if (s.length() < size) {
7+
return false;
8+
}
9+
10+
if (substr.equals("")) {
11+
substr = s.substring(0, size);
12+
} else {
13+
if (!substr.equals(s.substring(0, size))) {
14+
return false;
15+
}
16+
}
17+
}
18+
19+
return true;
20+
}
21+
22+
public String longestCommonPrefix(String[] strs) {
23+
int lo = 0, hi = 201, mid = 0;
24+
25+
for (int iter = 0; iter <= 8; iter++) {
26+
mid = (lo + hi) / 2;
27+
28+
if (isCommonForLength(mid, strs)) {
29+
lo = mid;
30+
} else {
31+
hi = mid;
32+
}
33+
}
34+
35+
return mid > 0 ? strs[0].substring(0, mid): "";
36+
}
37+
}

0 commit comments

Comments
 (0)