代码如下:
public class longestCommonPrefix {
/*
* 查找最长公共前缀
* 当字符串数组长度为 0 时则公共前缀为空,直接返回
* 令最长公共前缀 ans 的值为第一个字符串,进行初始化
* 遍历后面的字符串,依次将其与 ans 进行比较,两两找出公共前缀,最终结果即为最长公共前缀
* 如果查找过程中出现了 ans 为空的情况,则公共前缀不存在直接返回
* 时间复杂度:O(s)O(s),s 为所有字符串的长度之和
*/
public class test {
public String longestCommonPrefix(String[] arr) {
if (arr.length == 0) {
return "";
}
String lggqz = arr[0];
for (int i = 1; i < arr.length; i++) {
int j = 0;
for (; j < lggqz.length() && j < arr[i].length(); j++) {
if (lggqz.charAt(j) != arr[i].charAt(j)) {
break;
}
}
lggqz = lggqz.substring(0, j);
if (lggqz.length() == 0) {
return lggqz;
}
}
return lggqz;
}
public static void main(String[] args) {
longestCommonPrefix pro = new longestCommonPrefix();
String s = pro.longestCommonPrefix03(new String[] { "abc", "abcdef", "abcui" });
System.out.println(s);
}
}
输出:abc