diff --git a/README.md b/README.md index 13643147..8778b3dd 100644 --- a/README.md +++ b/README.md @@ -261,6 +261,7 @@ My accepted leetcode solutions to some of the common interview problems. - [Longest Word in Dictionary through Deleting](problems/src/string/LongestWordInDictonary.java) (Medium) - [Isomorphic Strings](problems/src/string/IsomorphicStrings.java) (Easy) - [String Compression](problems/src/string/StringCompression.java) (Easy) +- [Longest Common Prefix](problems/src/string/LongestCommonPrefix.java) (Easy) #### [Tree](problems/src/tree) diff --git a/problems/src/string/LongestCommonPrefix.java b/problems/src/string/LongestCommonPrefix.java new file mode 100644 index 00000000..716c459c --- /dev/null +++ b/problems/src/string/LongestCommonPrefix.java @@ -0,0 +1,34 @@ +package string; + +/** + * Created by gouthamvidyapradhan on 12/04/2018. + * Write a function to find the longest common prefix string amongst an array of strings. + * + * Solution: O(N x M) where N is the length of the given array and M is the max_length of a string. + */ +public class LongestCommonPrefix { + /** + * Main method + * @param args + */ + public static void main(String[] args) throws Exception{ + String[] A = {"abc", "a", "adkd"}; + System.out.println(new LongestCommonPrefix().longestCommonPrefix(A)); + } + + public String longestCommonPrefix(String[] strs) { + if(strs.length == 0) return ""; + String result = strs[0]; + for(int i = 1; i < strs.length; i ++){ + String s = strs[i]; + for(int j = 0; j < result.length(); j++){ + if(j >= s.length() || result.charAt(j) != s.charAt(j)) { + result = result.substring(0, j); + break; + } + } + } + return result; + } + +}