package com.lkr.dataStructure;
import java.util.Scanner;
//求一组字符串最大前缀
public class ZuiChangSubStr {
public static void main(String[] args){
/*System.out.println("请输入一组字符串");
Scanner input = new Scanner(System.in);
String [] arrays = new String[5];
for(int i = 0;i<arrays.length;i++){
arrays[i] = input.next();
}*/
//String [] arrays = new String[]{""};
//String [] arrays = new String[]{"abcd","ab","a"};
//String [] arrays = new String[]{"abcd","","a"};
String [] arrays = new String[]{"abcd","cf","a"};
String result = longSubStr(arrays);
if(result == ""){
System.out.println("存在空字符串或者数组为空");
}
else
System.out.println("最长前缀为:"+result);
}
//求最长前缀
public static String longSubStr(String [] strings){
String temp = strings[0];
//数组为0情况或者第一个字符串为空
if(strings.length == 0 || strings[0].equals("")){
System.out.println("数组为空");
return "";
}
//数组只有一个字符串情况
if(strings.length == 1){
return temp;
}
//遍历其他字符串进行比较
for (int i = 1;i<strings.length;i++){
//如果有其中一个字符串为空,则返回空
if(strings[i].length() == 0){
System.out.println("存在空字符串");
return "";
}
//temp的字符串长度最小
else if(temp.length() < strings[i].length()){
for (int j=0;j<temp.length();j++){
if(temp.charAt(j) != strings[i].charAt(j)){
temp = strings[i].substring(0,j);
break;
}
}
}
//string[i]长度最小
else {
for (int k=0;k<strings[i].length();k++){
if(temp.charAt(k) != strings[i].charAt(k)){
temp = strings[i].substring(0,k);
break;
}
//如果遍历完其中一个字符串,还没结束,返回该字符串
if(k == strings[i].length()-1){
temp = strings[i];
}
}
}
}
return temp;
}
}