package tx.one;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z
*/
public class Solution4 {
static String par="";
public static void main(String[] args) {
String[] nums={"fllower","fllower","fllowders"};
String s = longestCommonPrefix(nums);
System.out.println(s);
}
public static String longestCommonPrefix(String[] strs) {
/**
* 输入: ["flower","flow","flight"]
输出: "fl"
*/
//拿到第一个元素的最长前缀就是所有的公共最长前缀
String first=strs[0];
Boolean flg=false;
AtomicInteger count=new AtomicInteger(0);
for (int i = 1; i < strs.length; i++) {
String str = strs[i];
for (int j = 0; j < first.length(); j++) {
String s = first.substring(0, j + 1);
if(str.contains(s)){
par=s;
if(!flg){
count.incrementAndGet();
}
flg=true;
}else{
break;
}
}
flg=false;
}
if(count.intValue()==strs.length-1){
return par;
}else {
return "meiyou ";
}
}
}