编写一个函数来查找字符串数组中最长的公共前缀字符串。
package genius.wangyuxian.Algorithms;
public class WYX14 {
public static String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String pre = strs[0];//pre存储第一个字符串
int i = 1;//从第2个字符串开始寻找
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
//更新pre,直到找到,等于0的情况是截取完都没找到。
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
public static void main(String[] args) {
String[] strs = {"myttttpen","myttpen","mytpen"};
String string = longestCommonPrefix(strs);
System.out.println(string);
}
}
输出:
myt