-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathLongest_Common_Prefix_in_an_Array.java
38 lines (33 loc) · 1.15 KB
/
Longest_Common_Prefix_in_an_Array.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package string;
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] arr = { "program", "programmer", "programming" };
String pre = longestCommonPrefix(arr);
System.out.println(pre);
}
public static String longestCommonPrefix(String[] strs) {
if( strs == null || strs.length == 0 ){
return "";
}
return longestCommonPrefix(strs, 0, strs.length-1);
}
public static String longestCommonPrefix( String[] str, int l, int r ){
if( l == r ){
return str[l];
}else{
int mid = (l + r)/2;
String lcpleft = longestCommonPrefix( str, l, mid );
String lcpright = longestCommonPrefix( str, mid+1, r );
return commonPrefix( lcpleft, lcpright );
}
}
public static String commonPrefix( String left, String right ){
int min = Math.min( left.length(), right.length() );
for(int i = 0; i<min; i++){
if( left.charAt(i) != right.charAt(i) ){
return left.substring(0, i);
}
}
return left.substring(0, min);
}
}