一、题目描述
二、题目思路
- 以第一个字符串作为结果,去和其他的字符串进行比较
- 如果遇到了**更适合作为结果的字符串(长度短)**则更新
- 注意输入字符串数组中存在空字符串的情况
- 注意输入字符串数组为空的情况
三、提交代码
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length ==0){
return "";
}
String result = strs[0];
for(int i =1;i<strs.length;i++){
if(strs[i].length() ==0){
return "";
}
int j =0;
while(j<result.length() && j<strs[i].length()){
if(strs[i].charAt(j)!= result.charAt(j)){
result = result.substring(0,j);
}else if(j == strs[i].length()-1){
result = strs[i];
}
j++;
}
}
return result;
}
}