Write a function to find the longest common prefix string amongst an
array of strings.If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"] Output: "fl" Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no
common prefix among the input strings. Note:All given inputs are in lowercase letters a-z.
比较简单的一道题 按正向思维就可解
public String longestCommonPrefix(String[] strs) {
if(strs.length<=0) return "";
List<Integer> list=new ArrayList();
for(String s:strs) list.add(s.length());
int min=Collections.min(list);
StringBuilder builder=new StringBuilder();
for(int i=0;i<min;i++){
char c=strs[0].charAt(i);
for(int j=1;j<strs.length;j++){
if(c!=strs[j].charAt(i)) return builder.toString();
}
builder.append(c);
}
return builder.toString();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。