Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
返回字符串数组中所有字符串共有的最长前缀。easy难度,很简单,直接贴代码了。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0){
return "";
}
int len = strs[0].length();
StringBuilder sb = new StringBuilder();
for(int i=0;i<len;i++){
char c = strs[0].charAt(i);
sb.append(c);
for(int j=1;j<strs.length;j++){
if(strs[j].length()-1<i||strs[j].charAt(i)!=c){
return sb.toString().substring(0,i);
}
}
}
return sb.toString();
}
}
295

被折叠的 条评论
为什么被折叠?



