Skip to content

Commit

Permalink
Longest Common Prefix: Accepted
Browse files Browse the repository at this point in the history
  • Loading branch information
gouthampradhan committed Apr 12, 2018
1 parent 451bdff commit 25dfc53
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
34 changes: 34 additions & 0 deletions problems/src/string/LongestCommonPrefix.java
Original file line number Diff line number Diff line change
@@ -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;
}

}

0 comments on commit 25dfc53

Please sign in to comment.