Skip to content

Commit 2dec365

Browse files
author
Mrinal Chauhan
committed
Longest Common Prefix
1 parent 06137e3 commit 2dec365

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

src/main/java/com/thealgorithms/strings/LongestCommonPrefix.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ public static String longestPrefix(String[] str){
1515
if(n==0){
1616
return "";
1717
}
18+
/*
19+
Sort the Array: Sort the array of strings to bring strings with common prefixes adjacent to each other.
20+
Identify Extremes: Select the first and last strings from the sorted array for comparison, as they will have the longest common prefix.
21+
Character Comparison: Compare the characters of the first and last strings until a mismatch is found, tracking the index of the last matching character.
22+
Return Prefix: Return the substring of the first string from the start to the index of the last matching character, which represents the longest common prefix.
23+
*/
1824
String first=str[0];
1925
String last=str[n-1];
2026
int len=Math.min(first.length(),last.length());

0 commit comments

Comments
 (0)