题目介绍
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
步骤
【第一步】将字符串数组的第一个字符串作为公共前缀strs[0]。
【第二步】遍历字符串数组strs[i] i >= 1,和字符串strs[i]。
【第三步】对比公共前缀与字符串,并实时更新公共前缀
【第四步】返回结果
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
// 1. 设置第一个元素为最长公共前缀
String res = strs[0];
// 2.遍历字符串
for (int i = 1; i < strs.length; i++) {
int j = 0;
for (; j < res.length() && j < strs[i].length(); j++) {
// 3. 将公共前缀与字符串进行对比--如果不符合直接结束。
if (res.charAt(j) != strs[i].charAt(j)){
break;
}
}
// 4.更新公共前缀
res = res.substring(0,j);
// 4.1 如果j == 0,说明没有公共前缀,直接返回结果
if (j == 0) { // 剪枝
return "";
}
}
return res;
}