Write a function to find the longest common prefix string amongst an array of strings.
Have you met this question in a real interview?
思路: 很简单的一道题, 找到 字符串数组中 的最长前缀。 从第一个字符串开始, 和下一个字符串比较, 保留下来相同的字串。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String ret = strs[0];
for(int i = 1; i < strs.length; i++){
int min = Math.min(ret.length(), strs[i].length());
int j = 0;
while(j < min && ret.charAt(j) == strs[i].charAt(j)){
j++;
}
ret = ret.substring(0, j);
}
return ret;
}
}