题目: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]; TreeMaptopMap=new TreeMap (); for(int i=1;i str2.length()) { num=str2.length(); } else { num=str1.length(); } String top=""; //两个字符串相同的部分 for(int j=0;j