Skip to content

Commit e638861

Browse files
authored
Add LongestCommonPrefix.java
1 parent 640d823 commit e638861

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.thealgorithms.strings;
2+
3+
public final class LongestCommonPrefix {
4+
public String longestCommonPrefix(String[] strs) {
5+
if(strs == null || strs.length == 0) return "";
6+
7+
Arrays.sort(strs);
8+
String shortest = strs[0];
9+
String longest = strs[strs.length - 1];
10+
11+
int index = 0;
12+
while(index < shortest.length() && index < longest.length() && shortest.charAt(index) == longest.charAt(index))
13+
index++;
14+
15+
return shortest.substring(0, index);
16+
}
17+
}

0 commit comments

Comments
 (0)