forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Common_Prefix.java
More file actions
33 lines (29 loc) · 837 Bytes
/
Longest_Common_Prefix.java
File metadata and controls
33 lines (29 loc) · 837 Bytes
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
import java.util.*;
class Longest_Common_Prefix{
public static String LongestCommonPrefixFn(String[] strs) {
if(strs.length==0){
return "";
}
String st = strs[0];
for(int i=1; i<strs.length; i++){
while(strs[i].indexOf(st)!=0){
st = st.substring(0, st.length()-1);
}
}
return st;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter strings");
String st = sc.nextLine();
String[] arrOfStr = st.split(" ");
System.out.println("Longest Common Prefix : "+LongestCommonPrefixFn(arrOfStr));
}
}
/*sample input and output:
Enter strings
encourage encoder enchant
Longest Common Prefix : enc
Complexities
Time: O(n^2)
Space: O(n)*/