Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions problems/longest-common-prefix/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Longest Common Prefix

Given a String array, find the longest common prefix.

## Example

```
f([‘rocket’, ‘rockstar’, ‘rockbottom’, ‘rock’, ‘rollingstone’] // ‘ro’
f([‘shuffle’, ‘shuttle’, ‘shut’] // ‘shu’
```

## Source
Personal Phone Interview
20 changes: 20 additions & 0 deletions solutions/java/LongestCommonPrefix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class LongestCommonPrefix {
public static void main(String[] args) {
LongestCommonPrefix lcs = new LongestCommonPrefix();
String[] input = { "rocket", "rockstar", "rockbottom", "rollingstone"};
System.out.println(lcs.getSubstring(input));
}

public String getSubstring(String[] input) {
String base = input[0];
for (int i = 0; i < base.length(); i++) {
for (int j = 1; j < input.length; j++) { // Run for all words
String comparer = input[j];
if (i >= comparer.length()
|| comparer.charAt(i) != base.charAt(i))
return base.substring(0, i);
}
}
return "";
}
}