题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 :
输入: [“flower”,“flow”,“flight”]
输出: “fl”
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z
。
标签
字符串;递归
解题思路
方法一:横向扫描
依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。如果在尚未遍历完所有的字符串时,最长公共前缀已经是空串,则最长公共前缀一定是空串,因此不需要继续遍历剩下的字符串,直接返回空串即可。
方法二:纵向扫描
纵向扫描时,从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。
源自:https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode-solution/
代码
public class Leetcode14_LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
System.out.println(Leetcode14_LongestCommonPrefix.longestCommonPrefix1(strs));
}
//方法一:横向扫描:将每两个字符串进行比较后,再将公共部分与第三个比较
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String result = strs[0];
for (int i = 1; i < strs.length; i++) {
result = CommonPrefix(result, strs[i]);
}
return result;
}
//两个字符串的公共前缀
public static String CommonPrefix(String str1, String str2) {
if (str1.length() == 0 || str2.length() == 0) {
return "";
}
//最小公共前缀长度
int len = Math.min(str1.length(), str2.length());
//最小公共前缀
String result;
for (int i = 0; i < len; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
result = str1.substring(0, i);
return result;
}
}
return str1.substring(0, len);
}
//方法二:纵向扫描:将每个字符串第一列进行比较后,再将第二列进行比较,依次类推
public static String longestCommonPrefix1(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int len = strs[0].length();
int count = strs.length;
//行
for (int i = 0; i < len; i++) {
//列
char ch = strs[0].charAt(i);
for (int j = 1; j < count; j++) {
if (strs[j].charAt(i) != ch || i == strs[j].length()) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix/