-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestCommonPrefix.java
35 lines (29 loc) · 1.13 KB
/
LongestCommonPrefix.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
public class LongestCommonPrefix {
static String longestCommonPrefix(String[] strArr) {
if (strArr.length == 0) {
return "-1";
}
String miniLengthStr = strArr[0];
// Finding the minimum length string
for (String str : strArr) {
if (str.length() < miniLengthStr.length()) {
miniLengthStr = str;
}
}
int minLength = miniLengthStr.length();
for (int i = 0; i < minLength; i++) {
char currentChar = miniLengthStr.charAt(i);
for (String str : strArr) {
if (str.charAt(i) != currentChar) {
String commonPrefix = miniLengthStr.substring(0, i);
return commonPrefix.isEmpty() ? "-1" : commonPrefix;
}
}
}
return miniLengthStr.isEmpty() ? "-1" : miniLengthStr;
}
public static void main(String[] args) {
String strArr[] = { "geeksforgeeks", "geeks", "geek", "geezer" };
System.out.print("The Longest prefix is: " + longestCommonPrefix(strArr));
}
}