Write a function to find the longest common prefix string amongst an array of strings.
翻译
在字符串数组中找到最长的公共前缀。
分析
思路:当时的想法是找出最短的,它本身或者它的某一部分就是最长的公共前缀
1. 将字符串数组排序,最短的在第一个作为参考
2. 遍历,从第二个开始依次和第一个比较
3. 记录与第一个对比得出相同的前缀的个数
4. 在个数中最小的数字就是最长的公共前缀的位置不过这个想法太依赖排序了,这是我当时能想到的。更好的方法还是要去参考别人的。
java代码
class Solution {
public String longestCommonPrefix(String[] strs) {
//防止空的情况,和长度为1的直接返回本身
if (strs.length == 0 || strs[0].length() == 0) {
return "";
} else if (strs.length == 1) {
return strs[0];
}
Arrays.sort(strs);
char[] ch = strs[0].toCharArray();
int count, j = 0, len = strs.length - 1, min = Integer.MAX_VALUE;
while (len-- != 0) {
//初始化
count = 0;
//从第二个开始与第一个比较,记录有多少个相同前缀
for (int i = 0; i < ch.length; i++) {
if (strs[j + 1].charAt(i) == ch[i]) {
count++;
} else {
break;
}
}
//通过比较,得出最小前缀个数
if (count < min) {
min = count;
}
j++;
}
return String.valueOf(ch, 0, min);
}