Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit 88adb71

Browse files
committed
Merge pull request #130 from roitt/longest-common-prefix
Longest common prefix
2 parents 3e90f97 + 86c5444 commit 88adb71

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Longest Common Prefix
2+
3+
Given a String array, find the longest common prefix.
4+
5+
## Example
6+
7+
```
8+
f([‘rocket’, ‘rockstar’, ‘rockbottom’, ‘rock’, ‘rollingstone’] // ‘ro’
9+
f([‘shuffle’, ‘shuttle’, ‘shut’] // ‘shu’
10+
```
11+
12+
## Source
13+
Personal Phone Interview
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)