![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/18580f3812c5fc5107f137be0c363ddd.png)
提交
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0){
return "";
}
String ans = strs[0];
for(int i = 0; i < strs.length; i++){
int j = 0;
for(; j < ans.length() && j < strs[i].length(); j++){
if(ans.charAt(j) != strs[i].charAt(j)){
break;
}
}
ans = ans.substring(0, j);
if(ans.equals(""))
{
return ans;
}
}
return ans;
}
}
本地调用测试
package leetcode;
public class lc_14_longestCommonPrefix {
public static void main(String[] strs) {
String[] strst = new String []{"abc", "abcd", "abcde"};
for(int i = 0; i < strst.length; i++){
System.out.format("%s ", strst[i]);
}
lc_14_longestCommonPrefix arr = new lc_14_longestCommonPrefix();
String ans = arr.longestCommonPrefix(strst);
System.out.format("\n%s", ans);
}
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String ans = strs[0];
for(int i =1;i<strs.length;i++) {
int j=0;
for(;j<ans.length() && j < strs[i].length();j++) {
if(ans.charAt(j) != strs[i].charAt(j))
break;
}
ans = ans.substring(0, j);
if(ans.equals(""))
return ans;
}
return ans;
}
}