-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlongestprefix.java
More file actions
45 lines (37 loc) · 1.21 KB
/
longestprefix.java
File metadata and controls
45 lines (37 loc) · 1.21 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
37
38
39
40
41
42
43
44
45
package string;
public class longestprefix{
static String commonPrefixUtil(String str1, String str2) {
String result = "";
int n1 = str1.length(), n2 = str2.length();
// Compare str1 and str2
for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {
if (str1.charAt(i) != str2.charAt(j)) {
break;
}
result += str1.charAt(i);
}
return (result);
}
// A Function that returns the longest common prefix
// from the array of strings
static String commonPrefix(String arr[], int n) {
String prefix = arr[0];
for (int i = 1; i <= n - 1; i++) {
prefix = commonPrefixUtil(prefix, arr[i]);
}
return (prefix);
}
// Driver program to test above function
public static void main(String[] args) {
String arr[] = {"geeksforgeeks", "geeks",
"geek", "geezer"};
int n = arr.length;
String ans = commonPrefix(arr, n);
if (ans.length() > 0) {
System.out.printf("The longest common prefix is - %s",
ans);
} else {
System.out.printf("There is no common prefix");
}
}
}