forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
42 lines (35 loc) · 1.18 KB
/
LongestCommonPrefix.java
File metadata and controls
42 lines (35 loc) · 1.18 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
package com.thealgorithms.strings;
import java.util.Arrays;
/**
* Utility class for string operations.
* <p>
* This class provides a method to find the longest common prefix (LCP)
* among an array of strings.
* </p>
*
* @see <a href="https://en.wikipedia.org/wiki/Longest_common_prefix">Longest Common Prefix - Wikipedia</a>
*/
public final class LongestCommonPrefix {
private LongestCommonPrefix() {
}
/**
* Finds the longest common prefix among a list of strings using lexicographical sorting.
* The prefix is common to the first and last elements after sorting the array.
*
* @param strs array of input strings
* @return the longest common prefix, or empty string if none exists
*/
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
Arrays.sort(strs);
String first = strs[0];
String last = strs[strs.length - 1];
int index = 0;
while (index < first.length() && index < last.length() && first.charAt(index) == last.charAt(index)) {
index++;
}
return first.substring(0, index);
}
}