mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 00:54:32 +08:00
Add LongestCommonPrefix (#5849)
This commit is contained in:

committed by
GitHub

parent
84522baa92
commit
3da16a7fe0
@ -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);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user