Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.
import java.util.*;
import java.lang.Character;
class Solution {
public int maxLength(List<String> arr) {
int N = arr.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < (1<<N); i++) {
List<Integer> combination = new ArrayList<>();
for (int j = 0; j < arr.size(); j++) {
if ((i & (1 << j)) > 0) {
combination.add(j);
}
}
int count = getDistinctCount(arr, combination);
if (count > max){
max = count;
}
}
return max;
}
public int getDistinctCount(List<String> A, List<Integer> combination) {
Map<Character, Integer> charMap = new HashMap<>();
for (int i = 0; i < combination.size(); i++) {
String word = A.get(combination.get(i));
for (int j = 0; j < word.length(); j++) {
if (charMap.containsKey(Character.valueOf(word.charAt(j)))) {
return 0;
}
charMap.put(Character.valueOf(word.charAt(j)), 1);
}
}
return charMap.keySet().size();
}
}
#codingexercise:
No comments:
Post a Comment