public class Solution {
/*
*
* 14. Longest Common Prefix
* Write a function to find the longest common prefix string amongst an array of strings.
* My stupid solution with O(n^2) Complexity.
*
* */
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0)
return "";
String start = strs[0];
for(int i = 1; i <= start.length(); i++){
for(String s: strs){
if(s.length() < i || !s.substring(0,i).equals(start.substring(0,i))){
return start.substring(0,i-1);
}
}
}
return start;
}
}
/*
* method 2:
* want the longest
* choose the first string in the array
* and shrink it until to the end
* */
public static String longestCommonPrefix2(String[] strs) {
// corner case
if(strs == null || strs.length == 0)
return "";
String prefix = strs[0];
for(int i = 1; i < strs.length; i++){
while(strs[i].indexOf(prefix) != 0 ){
prefix = prefix.substring(0,prefix.length()-1);
if(prefix == "")
return "";
}
}
return prefix;
}