最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀 如果不存在公共前缀 返回空我字符串 " "
进行一个 字符的比对 ;返回核对前缀的字符串。
package LeeCodeTest14;
/**
* 最长公共前缀
* 编写一个公共函数 来查找字符串数组中的最长公共前缀
* 如果不存在公共前缀 返回空字符串 " "。
*/
public class LeeCodeTest14 {
public String longestCommonPrefix(String[] Str){
//查找公共前缀 查找数组中的字符串中的公共前缀
//首先我们的前提是寻找出字符串的公共前缀
//我们不断进行测试怎么测试呢 我们将数组中的第一个字符串作为一个标本;
//将第一个字符串不断的和数组中的元素进行循环遍历比较直到 我们的公共字符串找到就返回
String s =Str[0];
for (String string :Str
) {
while (!string.startsWith(s)){
if(s.length()==0)
return "";
//公共前缀不匹配的时候我们将数组中的第一个字符串进行缩小直到找到那个公共字符串 缩小的方法使用的是 subString进行对字符串的剪切
s=s.substring(0,s.length()-1);
}
}
return s;
}
public static void main(String[] args) {
LeeCodeTest14 test = new LeeCodeTest14();
String[] Str= new String[]{"flower","flow","flight","fl","fli"};
String s = test.longestCommonPrefix(Str);
System.out.println(s);
}
}