diff --git a/problems/longest-common-prefix/Readme.md b/problems/longest-common-prefix/Readme.md new file mode 100644 index 0000000..b600922 --- /dev/null +++ b/problems/longest-common-prefix/Readme.md @@ -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 diff --git a/solutions/java/LongestCommonPrefix.java b/solutions/java/LongestCommonPrefix.java new file mode 100644 index 0000000..b2b8a22 --- /dev/null +++ b/solutions/java/LongestCommonPrefix.java @@ -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 ""; + } +} \ No newline at end of file