LeetCode13-Longest-Common-Prefix

51次阅读

共计 715 个字符,预计需要花费 2 分钟才能阅读完成。

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();}

正文完
 0