牛客题目链接
1. 题目考点
- 数组特殊情况处理
- 字符串比较
2. 考点解析
- 直接遍历数组(最容易想到)
public String longestCommonPrefix (String[] strs) {
if (strs == null || strs.length == 0) return "";
if (strs.length == 1) return strs[0];
String res = strs[0];
for (int i = 1; i < strs.length; i++) {
res = f(res, strs[i]);
}
return res;
}
public String f(String s1, String s2) {
String res = "";
int i = 0, j = 0;
while (i < s1.length() && j < s2.length()) {
if (s1.charAt(i) != s2.charAt(j)) return res;
res += s1.charAt(i);
i++;
j++;
}
return res;
}