题目:
编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 说明: 所有输入只包含小写字母 a-z 。
解法一:直接从头开始扫描。
代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
String str = "";
if (strs.length == 0) {
return "";
}
String temp = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(temp) != 0) {
temp = temp.substring(0, temp.length() - 1);
if (temp.isEmpty()) {
return "";
}
}
}
str = temp;
return str;
}
}