Created
November 14, 2017 21:59
-
-
Save shailrshah/322e2df0c3b091955fdc2b88ab802758 to your computer and use it in GitHub Desktop.
Find the longest common prefix for a given array of strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public String longestCommonPrefix(String[] strs) { | |
if(strs == null || strs.length == 0) | |
return ""; | |
int minLength = getMinLength(strs); | |
for(int i = 0; i < minLength; i++) { //For each index | |
char ch = strs[0].charAt(i); | |
for(int j = 1; j < strs.length; j++){ // For each string | |
if(strs[j].charAt(i) != ch) | |
return strs[0].substring(0, i); | |
} | |
} | |
return strs[0].substring(0, minLength); | |
} | |
private int getMinLength(String[] strs){ | |
int min = strs[0].length(); | |
for(int i = 1; i < strs.length; i++){ | |
min = Math.min(strs[i].length(), min); | |
} | |
return min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment