Add LongestCommonPrefix (#5849)

This commit is contained in:
Ramit Gangwar (NoiR)
2024-10-27 00:31:47 +05:30
committed by GitHub
parent 84522baa92
commit 3da16a7fe0
3 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package com.thealgorithms.strings;
import java.util.Arrays;
public final class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
Arrays.sort(strs);
String shortest = strs[0];
String longest = strs[strs.length - 1];
int index = 0;
while (index < shortest.length() && index < longest.length() && shortest.charAt(index) == longest.charAt(index)) {
index++;
}
return shortest.substring(0, index);
}
}