-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCP.java
More file actions
36 lines (34 loc) · 1.01 KB
/
Copy pathLCP.java
File metadata and controls
36 lines (34 loc) · 1.01 KB
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
public class LCP {
static int minLength(String arr[], int n){
int min = arr[0].length();
for(int i=1;i<n;i++){
if(arr[i].length() <min){
min = arr[i].length();
}
}
return min;
}
static String commonPrefix(String arr[], int n){
int minLen = minLength(arr,n);
String ans ="";
for(int i=0;i<minLen;i++){
char current = arr[0].charAt(i);
for(int j=1;j<n;j++){
if(arr[j].charAt(i) != current){
return ans;
}
}
ans += current;
}
if(ans.isEmpty()){
System.out.println("NO COMMON PREFIX FOUND");
}
return ans;
}
public static void main(String[] args) {
String arr[] = {"like", "listen","lies","lists","long"};
int n = arr.length;
String ans = commonPrefix(arr, n);
System.out.println("LCP FOUND :" + ans );
}
}