Clicky

Leetcode 1239 "Maximum Length of a Concatenated String with Unique Characters"

January 1, 0001

1239. Maximum Length of a Concatenated String with Unique Characters

Result

Runtime: 39 ms, faster than 23.63% of Java online submissions for Maximum Length of a Concatenated String with Unique Characters.

Memory Usage: 38.9 MB, less than 38.68% of Java online submissions for Maximum Length of a Concatenated String with Unique Characters.

class Solution {
    public int maxLength(List<String> arr) {
        return maxLengthRec(arr, 0, "");
    }
    
    public int maxLengthRec(List<String> arr, int index, String word) {
        if(index > arr.size()-1)
            return 0 ;
        
        int thisRun1 = 0;
        String word1 = word + arr.get(index);
        if(valid(word1)) {
            thisRun1 = Math.max(word1.length(), maxLengthRec(arr, index + 1, word1));
        }
        int thisRun2 = 0;
        String word2 = word;
        if(valid(word2)) {
            thisRun2 = Math.max(word2.length(), maxLengthRec(arr, index + 1, word2));
        }        
        
        return Math.max(thisRun1, thisRun2);
    }
           
    public boolean valid(String str) {
        Set<Character> set = new HashSet<>();
        for(int i=0; i< str.length(); i++) {
            if(set.contains(str.charAt(i)))
                return false;
            else
                set.add(str.charAt(i));
        }
        return true;
    }
}