-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_27.java
More file actions
34 lines (26 loc) · 1.02 KB
/
Problem_27.java
File metadata and controls
34 lines (26 loc) · 1.02 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
package strings;
// *Find Longest Common Prefix
public class Problem_27 {
public static String findLongestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return ""; // Empty array or null input
}
String prefix = strs[0]; // Initialize with the first string
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
// Shorten the prefix if it's not a prefix of the current string
prefix = prefix.substring(0, prefix.length() - 1);
// Handle cases where there is no common prefix
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
public static void main(String[] args) {
String[] strs = { "flower", "flow", "flight" };
String lcp = findLongestCommonPrefix(strs);
System.out.println("Longest Common Prefix for [" + String.join(", ", strs) + "] is: " + lcp);
}
}