Skip to content

Commit 86c5444

Browse files
committed
Longest common prefix solution Java
1 parent 7312b2d commit 86c5444

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class LongestCommonPrefix {
2+
public static void main(String[] args) {
3+
LongestCommonPrefix lcs = new LongestCommonPrefix();
4+
String[] input = { "rocket", "rockstar", "rockbottom", "rollingstone"};
5+
System.out.println(lcs.getSubstring(input));
6+
}
7+
8+
public String getSubstring(String[] input) {
9+
String base = input[0];
10+
for (int i = 0; i < base.length(); i++) {
11+
for (int j = 1; j < input.length; j++) { // Run for all words
12+
String comparer = input[j];
13+
if (i >= comparer.length()
14+
|| comparer.charAt(i) != base.charAt(i))
15+
return base.substring(0, i);
16+
}
17+
}
18+
return "";
19+
}
20+
}

0 commit comments

Comments
 (0)