编写一个函数来查找字符串数组中的最长公共前缀
https://leetcode-cn.com/problems/longest-common-prefix/
示例1:
示例2:
提示:
Java解法
package sj.shimmer.algorithm;
/**
* Created by SJ on 2021/2/2.
*/
class D9 {
public static void main(String[] args) {
System.out.println(longestCommonPrefix(new String[]{"flower","flow","flight"}));
System.out.println(longestCommonPrefix(new String[]{"dog","racecar","car"}));
System.out.println(longestCommonPrefix(new String[]{"cir","car"}));
System.out.println(longestCommonPrefix(new String[]{"flower","fkow"}));
}
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++) {
String common = getCommonPre(result, strs[i]);
if (common!=null&&common!="") {
result = common;
}else {
return "";
}
}
return result;
}
public static String getCommonPre(String s1, String s2) {
int i = 0;
String result = "";
while (i<s1.length()&&i<s2.length()){
if (s1.charAt(i)==s2.charAt(i)) {
result+=s1.charAt(i);
}else {
return result;
}
i++;
}
return result;
}
}
官方解
-
横向扫描
- 时间复杂度: O(mn),其中 m是字符串数组中的字符串的平均长度,n是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次
- 空间复杂度: O(1)。使用的额外空间复杂度为常数
-
纵向扫描
- 时间复杂度: O(mn),其中 m是字符串数组中的字符串的平均长度,n是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次
- 空间复杂度: O(1)。使用的额外空间复杂度为常数
-
分治
- 时间复杂度:O(mn),其中 m 是字符串数组中的字符串的平均长度,nn 是字符串的数量。
- 空间复杂度:O(mlogn),其中 m 是字符串数组中的字符串的平均长度,nn 是字符串的数量。空间复杂度主要取决于递归调用的层数,层数最大为 log n,每层需要 m 的空间存储返回结果# Day9 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀
https://leetcode-cn.com/problems/longest-common-prefix/
示例1:
示例2:
提示:
Java解法
package sj.shimmer.algorithm;
/**
* Created by SJ on 2021/2/2.
*/
class D9 {
public static void main(String[] args) {
System.out.println(longestCommonPrefix(new String[]{"flower","flow","flight"}));
System.out.println(longestCommonPrefix(new String[]{"dog","racecar","car"}));
System.out.println(longestCommonPrefix(new String[]{"cir","car"}));
System.out.println(longestCommonPrefix(new String[]{"flower","fkow"}));
}
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++) {
String common = getCommonPre(result, strs[i]);
if (common!=null&&common!="") {
result = common;
}else {
return "";
}
}
return result;
}
public static String getCommonPre(String s1, String s2) {
int i = 0;
String result = "";
while (i<s1.length()&&i<s2.length()){
if (s1.charAt(i)==s2.charAt(i)) {
result+=s1.charAt(i);
}else {
return result;
}
i++;
}
return result;
}
}
官方解
-
横向扫描
- 时间复杂度: O(mn),其中 m是字符串数组中的字符串的平均长度,n是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次
- 空间复杂度: O(1)。使用的额外空间复杂度为常数
-
纵向扫描
- 时间复杂度: O(mn),其中 m是字符串数组中的字符串的平均长度,n是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次
- 空间复杂度: O(1)。使用的额外空间复杂度为常数
-
分治
- 时间复杂度:O(mn),其中 m 是字符串数组中的字符串的平均长度,nn 是字符串的数量。
- 空间复杂度:O(mlogn),其中 m 是字符串数组中的字符串的平均长度,nn 是字符串的数量。空间复杂度主要取决于递归调用的层数,层数最大为 log n,每层需要 m 的空间存储返回结果