美文网首页算法提高之LeetCode刷题
LeetCode-14:Longest Common Prefi

LeetCode-14:Longest Common Prefi

作者: 大数据Zone | 来源:发表于2018-09-15 12:57 被阅读1次

题目描述:

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.

我的第一反应代码

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs==null || strs.length==0)
            return "";
        
        int maxlen=Integer.MAX_VALUE;
        for(String str:strs){
            int len = str.length();
            maxlen = maxlen>len? len:maxlen;
        }
        int common = 0;
        boolean goon = true;
        //从第一个下标开始遍历
        for(int i=0;i<maxlen;i++){
            HashMap<String,Integer> hashmap = new HashMap<String,Integer>();
            hashmap.put(String.valueOf(strs[0].charAt(i)), 0);    
            for(int j=1;j<strs.length;j++){
                if(!hashmap.containsKey(String.valueOf(strs[j].charAt(i)))){
                    goon = false;
                    break;
                }        
            }
            if(goon)
                common=common+1;
            else
                break;        
        }
        return strs[0].substring(0,common);
    }
}

别人的比较好的分析:

https://www.jianshu.com/p/63dcc0d7db75

相关文章

网友评论

    本文标题:LeetCode-14:Longest Common Prefi

    本文链接:https://www.haomeiwen.com/subject/ogwzgftx.html