首页 > 代码库 > LeetCode-- Longest Common Prefix

LeetCode-- Longest Common Prefix

题目:

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

第一种解决方案:

public class Solution {
    public  String longestCommonPrefix(String[] strs) {
	        int strslen=strs.length;
	        if(strslen==0) return "";
	       
	        String temp=null;
	        for(int i=0;i<strslen;i++){
	        StringBuilder sb=new StringBuilder();
	            if(i==0){
	                temp=strs[0];
	                continue;
	            }
	         int tlen=temp.length();
	         int ilen=strs[i].length();
	         int len=0;
	         len=(tlen>=ilen)?ilen:tlen;
	         for(int j=0;j<len;j++){
	             Character c=temp.charAt(j);
	             if(!c.equals(strs[i].charAt(j))){
	                 int sblen=sb.length();
	                 if(sblen==0) return "";
	                 break;
	             }else{
	                 sb.append(c);
	             }

	         } temp=sb.toString();
	        }
	        return temp;
	    }
}

经过思考,觉得完全没有必要引入StringBuilder,所以有了第二种解决方案并且效率较优。

第二种解决方案:

public class Solution {
    public  String longestCommonPrefix(String[] strs) {
	        int strslen=strs.length;
	        if(strslen==0) return "";
	       
	        String temp=strs[0];
	        for(int i=1;i<strslen;i++){
	         int tlen=temp.length();
	         int ilen=strs[i].length();
	         int len=0;
	         len=(tlen>=ilen)?ilen:tlen;
	         int j;
	         for( j=0;j<len;j++){
	             Character c=temp.charAt(j);
	             if(!c.equals(strs[i].charAt(j))){
	                 break;
	             }
	         }	
	         temp=temp.substring(0,j);
	        }
	        return temp;
	    }
}


LeetCode-- Longest Common Prefix