mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
refactor: adding docs for LongestCommonPrefixTest and Parameterized Tests (#6360)
* refactor: adding docs for LongestCommonPrefixTest and Parameterized Tests * checkstyle: fix clang formatting --------- Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
parent
3e0fd11a96
commit
048bba9499
@@ -2,21 +2,41 @@ 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 {
|
||||
public String longestCommonPrefix(String[] strs) {
|
||||
|
||||
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 shortest = strs[0];
|
||||
String longest = strs[strs.length - 1];
|
||||
String first = strs[0];
|
||||
String last = strs[strs.length - 1];
|
||||
|
||||
int index = 0;
|
||||
while (index < shortest.length() && index < longest.length() && shortest.charAt(index) == longest.charAt(index)) {
|
||||
while (index < first.length() && index < last.length() && first.charAt(index) == last.charAt(index)) {
|
||||
index++;
|
||||
}
|
||||
|
||||
return shortest.substring(0, index);
|
||||
return first.substring(0, index);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user