题目:
写一个函数来查找字符串数组中最长的公共前缀字符串。例如,
input: [“13”,”12”] output: “1”
input: [“13”,”12”,”123”] output: “1”
input: [“13”,”12”,”23”] output: “”
input: [“1312”,”12”,”123”] output: “1”
思路:
取字符串数组中的第一个作为最长的公共前缀字符串,与其他进行对比,若不匹配,则将其第一个的长度减一再与其他匹配。
代码:
public String longestCommonPrefix(String[] strs) {
//若输入数组是null或为空,则返回""
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
//通过i++和while循环让遍历数组中每个串
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}