题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
思路:
横向扫描
用LCP(S1. ..Sn)表示字符串S1...Sn的最长公共前缀。
可以得到以下结论:
LCP(S1 . .. Sn))= LCP(LCP(LCP(S1,S2),S3), . ..Sn)
基于该结论,可以得到一种查找字符串数组中的最长公共前缀的简单方法。
依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,
当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。
如果在尚未遍历完所有的字符串时,最长公共前缀已经是空串,则最长公共前缀一定是空串,
因此不需要继续遍历剩下的字符串,直接返回空串即可。
代码:
import java.util.Scanner;
public class 最长公共前缀2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] strs = { "flower", "flow", "flight" };
System.out.println(getMax(strs));
}
private static String getMax(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String a = strs[0];
for (int i = 1; i < strs.length; i++) {
String b = strs[i];
a = getMax(a, b);
}
return a;
}
private static String getMax(String a, String b) {
int index = 0;
int len = Math.min(a.length(), b.length());
while (index < len && a.charAt(index) == b.charAt(index)) {
index++;
}
return a.substring(0, index);
}
}