Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Note:
All given inputs are in lowercase letters a-z
.
public class LongestCommonPrefixSolution {
public String longestCommonPrefix(String[] strs) {
//基本思路为贪心算法,每两个元素取最长的公共元素,依次往下进行
if (strs.length > 0) {
String result = strs[0];
int len = strs.length;
for (int j = 1; j < len; j++) {
while (!strs[j].startsWith(result)) {
result = result.substring(0, result.length() - 1);
}
}
return result;
} else {
return "";
}
}
}