最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 " "。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:""
解释:输入不存在公共前缀。
水平扫描
class Solution {
public String longestCommonPrefix(String[] strs) {
int n = strs.length;
if (n == 0 || strs[0].length() == 0) {
return "";
} else if (n == 1) {
return strs[0];
}
StringBuilder pub = new StringBuilder();
int min_length = strs[0].length();
for (int i = 1; i < n; i++) {
min_length = Math.min(min_length, strs[i].length());
}
if (min_length == 0) {
return "";
}
int index = 0;
while (index < min_length) {
char c = strs[0].charAt(index);
for (int i = 1; i < n; i++) {
if (strs[i].charAt(index) != c) {
return pub.toString();
}
}
pub.append(c);
index++;
}
return pub.toString();
}
}