leetcode
class Solution {
public String longestCommonPrefix(String[] strs) {
int length = strs.length;
if(length == 0){
return "";
}
// 记录最长公共前缀的位置
int end = 0;
boolean same = true;
// 如果每个单词对应位置的字符相同 且 end的位置没有越界
while(same && strs[0].length() > end){
// 获取第一个单词的对应字母,分别和其他单词进行比较
char first = strs[0].charAt(end);
for(String str : strs){
// 如果单词已经全部匹配结束 或者 单词的end位置字母不匹配
// 说明整个匹配过程已经结束
if(str.length() == end || str.charAt(end) != first){
same = false;
break;
}
}
// 只有same为true,end才可以继续+1
if(same){
end++;
}
}
return strs[0].substring(0, end);
}
}