Find min,then compare every str with the min


  • 0
    A

    the idea is simple :
    1、find the min length in string array
    2、compare every string with the min to find longest common prefix

    public String longestCommonPrefix(String[] strs) {
            
        	if(strs == null || strs.length <= 0)return "";
        	if(strs.length == 1)return strs[0];
        	
        	int minIndex = -1;
        	int minLength = Integer.MAX_VALUE;
        	for(int i = 0; i < strs.length; i ++){
        		if(strs[i].length() < minLength){
        			minLength = strs[i].length();
        			minIndex = i;
        		}
        	}
        	
        	while(minLength > 0){
        	
        		String minStr = strs[minIndex].substring(0, minLength);
        		int i = 0;
        		for(; i < strs.length; i ++){
        			if(!strs[i].substring(0, minLength).equals(minStr))
        				break;
        	    }
        		if(i >= strs.length)break;
        		minLength --;
        	}
        	return strs[minIndex].substring(0, minLength);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.