leetcode14.最长公共前缀(字符串匹配)

public class LeetCode14 {

public String newBigPrefix(String[] strs){
//标记数据
int y=0,z=0;
//返回字符串
String num="";
//返回字符串数组中值最小的下标
for(int i=1;i<strs.length;i++){
if(strs[z].length()<=strs[i].length()){

}else z=i;
}
//判断字符串数组是否为空,不判断如果为空会报异常
if(strs==null||strs.length==0){
return num;
}
//双重循环,第一重循环选择字符串中的字符,第二重循环选择字符串
//第一重循环选择字符,以最小字符串为判断元素
for(int i=0;i<strs[z].length();i++){
for(int j=1;j<strs.length;j++){
//判断每组字符串字符是否相同,并标记,如果全部相同则进行添加,不相同则返回
if(strs[j-1].charAt(i)==strs[j].charAt(i)){
y++;
}
}
//根据y判断是否添加
if(y==strs.length-1){
num+=strs[z].charAt(i);
y=0;
}else {
return num;
}
}
return num;
}

//这是垃圾,代码十分多余
public String bigPrefix(String example, String example1, String example2){
int a = 0,b = 0;
String num=new String();
//判断三个字符串大小,并进行标记,获得最小字符串
if(example.length()>example1.length()){
if(example1.length()>=example2.length()){
a=2;
}
if(example2.length()>=example.length()){
a=1;
}
}else {
if(example.length()>=example2.length()){
a=2;
}
if(example2.length()>=example1.length()){
a=0;
}
}
//选择最小字符串作为循环判断条件
if(a==0){
for(int i=0;i<example.length();i++){
//如果三个字符串都匹配,则继续判断下一个,直到失败(同时以b判断第一个是否成功匹配)
if(example.charAt(i)==example1.charAt(i)&&example1.charAt(i)==example2.charAt(i)){
b++;
num+=example.charAt(i);
}
//如果b=0,则意味着未判断成功,输出空值
if(b==0){
return "";
}
//如果b=i+1,意味着循环次数不等于成功匹配次数,意味着存在匹配失败,此时直接返回已匹配字符串
if(b!=i+1){
return num;
}
}
return num;
}
//下面同理
if(a==1){
for(int i=0;i<example1.length();i++){
if(example.charAt(i)==example1.charAt(i)&&example1.charAt(i)==example2.charAt(i)){
b++;
num+=example1.charAt(i);
}
if(b==0){
return "";
}
if(b!=i+1){
return num;
}
}
return num;
}
if(a==2){
for(int i=0;i<example2.length();i++){
if(example.charAt(i)==example1.charAt(i)&&example1.charAt(i)==example2.charAt(i)){
b++;
num+=example2.charAt(i);
}
if(b==0){
return "";
}
if(b!=i+1){
return num;
}
}
return num;
}
return null;
}

public static void main(String args[]){
LeetCode14 leedCode14=new LeetCode14();
String strs[]={};
System.out.println("公共前缀为:"+leedCode14.newBigPrefix(strs));
}

}

/**leetcode提交代码
* 切记切记切记!!一定要判断字符串数组是否为空!否则极易出现下标溢出错误
* public String newBigPrefix(String[] strs){
* int y=0,z=0;
* String num="";
* for(int i=1;i<strs.length;i++){
* if(strs[z].length()<=strs[i].length()){
*
* }else z=i;
* }
* //判断字符串数组是否为空,不判断如果为空会报异常
* if(strs==null||strs.length==0){
* return num;
* }
* for(int i=0;i<strs[z].length();i++){
* for(int j=1;j<strs.length;j++){
* if(strs[j-1].charAt(i)==strs[j].charAt(i)){
* y++;
* }
* }
* if(y==strs.length-1){
* num+=strs[z].charAt(i);
* y=0;
* }else {
* return num;
* }
* }
* return num;
* }
*/
原文地址:https://www.cnblogs.com/shudaixiongbokeyuan/p/13368980.html