【LeetCode】Longest Common Prefix

题目:Write a function to find the longest common prefix string amongst an array of strings.

 

这题的意思是,求字符串数组中的所有字符串的公共头。

解题思路:由于要求所有字符串的公共头,和求几个整数的公约数一样。我们先将字符串数组中的相邻元素进行比较,取出相同的部分,放入一个TreeMap中,其中TreeMap的key为相同部分字符串的长度,值为相同部分的字符串。最后取出最小的key即可。

class Solution {
    public String longestCommonPrefix(String[] strs) {
         int len=strs.length;
        if(len==0)
            return "";
        if(len==1)
            return strs[0];
        TreeMap<Integer,String> topMap=new TreeMap<Integer,String>();
        for(int i=1;i<len;i++)
        {
            String str1=strs[i-1];
            String str2=strs[i];
            int num=0;
            if(str1.length()>str2.length())
            {
                 num=str2.length();
            }
            else
            {
                 num=str1.length();
            }
            String top="";  //两个字符串相同的部分
            for(int j=0;j<num;j++)
            {
                if(str1.charAt(j)==str2.charAt(j))
                {
                    top+=str1.charAt(j);
                }
                else
                {
                    break;
                }
            }
            topMap.put(top.length(), top);//TreeMap如果不进行特殊处理的话,默认升序排列
            
        }
        int key=topMap.firstKey();  
        return topMap.get(key);
    }
}

 

posted @ 2017-11-13 17:52  contixue  阅读(148)  评论(0编辑  收藏  举报