题目链接
https://leetcode.cn/problems/longest-common-prefix/
题目描述
题解
题解1
众所周知,好多个字符串的公共前缀,一定取决于最小的那个字符串
所以,我们可以先拿两个字符串求公共前缀,然后拿求出的公共前缀再继续和后面的求公共前缀
一直和最后一个字符串求完公共前缀,我们就得到了所有字符串的公共前缀
public String longestCommonPrefix(String[] strs) {
String pre = strs[0];
for (int i = 1; i < strs.length; i++) {
// 计算strs[i]和公共前缀的公共前缀
pre = m(strs[i], pre);
if(pre.length() == 0)
return "";
}
return pre;
}
/**
求两个字符串的公共前缀,没有返回null
*/
public String m(String s1, String s2) {
int index = 0;
while(index < s1.length() && index < s2.length()) {
if (s1.charAt(index) == s2.charAt(index))
index++;
else
break;
}
return s1.substring(0, index);
}