Write a function to find the longest common prefix string amongst an array of strings.
给了一个string数组,求这些字符串的最长公共前缀。
思路:按列比较,复杂度O(mn)。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0)
return "";
for (int i = 0; i < strs[0].length(); ++i) {
for (int j = 0; j < strs.length - 1; ++j) {
if (!(i < strs[j].length() && i < strs[j + 1].length() && strs[j].charAt(i) == strs[j + 1].charAt(i)))
return strs[0].substring(0, i);
}
}
return strs[0];
}
}