Longest Common Prefix Java Solution


  • -1
    V

    public class Solution {

    public String longestCommonPrefix(String[] strs) {
    
        if(strs == null){
            return null;
        }
    
        if(strs.length == 0){
            return "";
        }
        
        if(strs.length == 1){
            return strs[0];
        }
    
        //find the min length strs, because the possible maximum length of common prefix is the minimum length among them.
        int length = strs[0].length();
        for(int i = 1; i < strs.length; i++){
            length = Math.min(length, strs[i].length());
        }
        
        if(length == 0){
            return "";
        }
        
        StringBuilder sb = new StringBuilder();
        //find strs[0], strs[1]...strs[k] jth char, 
        for(int j = 0; j < length; j++){
            for(int k = 0; k < strs.length - 1; k++){
                if(strs[k].charAt(j) != strs[k+1].charAt(j)){
                    return sb.toString();
                }
            }
    
            sb.append(strs[0].charAt(j));
        }
        
        return sb.toString();
        
        
    }
    

    }


Log in to reply
 

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