leetcode第14题要求:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
先来讲下思路:
1.先取出字符串数组0. 用其他数去好它进行对比
2.拿其他字符串和它进行对比。因为是对比前缀,所以可以用Startwith判断是否开头包含
3.假设s0的字符串为:s0="flo" . 其他字符串“flow”,"fllwer"
4.如果包含就退出循环,用下一个字符串去判断
5.因为s0=flo,和其他字符串相比,前缀多了个o.所以,只需要把最后一个不符合的去掉。剩下的就是前缀。
剩下的就是前缀。
//先讲解下思路。
if(strs.length==0){
return "";
}
//1.先取出字符串数组0. 用其他数去好它进行对比
String s0 = strs[0];
//2.拿其他字符串和它进行对比。因为是对比前缀,所以可以用Startwith判断是否开头包含
for (String s : strs){
//假设s0的字符串为:s0="flo" . 其他字符串“flow”,"fllwer"
while (!s.startsWith(s0)){//如果包含就退出循环,用下一个字符串去判断
if(s0.length()==0) return "";
//因为s0=flo,和其他字符串相比,前缀多了个o.所以,只需要把最后一个不符合的去掉。剩下的就是前缀。
s0 = s0.substring(0,s0.length()-1);//切掉尾巴,s0=“fl”.
}
}
return s0;
提供下所有的代码,可供测试
package com.zhm.test;
/**
* @Author bige
* @Date: 2022/11/25 8:44
* @ApiNote:最长公共前缀
*/
public class Leetcode_test014 {
//ApiNote:编写一个函数来查找字符串数组中的最长公共前缀。
//如果不存在公共前缀,返回空字符串 ""。
public static String longestCommonPrefix(String[] strs) {
//先讲解下思路。
if(strs.length==0){
return "";
}
//1.先取出字符串数组0. 用其他数去好它进行对比
String s0 = strs[0];
//2.拿其他字符串和它进行对比。因为是对比前缀,所以可以用Startwith判断是否开头包含
for (String s : strs){
//假设s0的字符串为:s0="flo" . 其他字符串“flow”,"fllwer"
while (!s.startsWith(s0)){//如果包含就退出循环,用下一个字符串去判断
if(s0.length()==0) return "";
//因为s0=flo,和其他字符串相比,前缀多了个o.所以,只需要把最后一个不符合的去掉。剩下的就是前缀。
s0 = s0.substring(0,s0.length()-1);//切掉尾巴,s0=“fl”.
}
}
return s0;
}
public static void main(String[] args) {
String[] test1={"flower","flow","flight"};
String[] test2={"dog","cat","car"};
String[] test3={"sdfhe","wehe","fshe"};
//longestCommonPrefix(test1);
System.out.println(longestCommonPrefix(test1));
}
}
最后算法分析: