classSolution {
publicintmaxLength(List<String> arr) {
return helper(arr, 0, "");
}
privateinthelper(List<String> arr, int start, String current) {
if (!isUnique(current)) return 0;
int ans = current.length();
for (int i = start; i < arr.size(); i++) {
ans = Math.max(ans, helper(arr, i + 1, current + arr.get(i)));
}
return ans;
}
privatebooleanisUnique(String s) {
Set<Character> set =new HashSet<>();
for (char c : s.toCharArray()) {
if (set.contains(c)) returnfalse;
set.add(c);
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defmaxLength(self, arr: List[str]) -> int:
return self.helper(arr, 0, "")
defhelper(self, arr: List[str], start: int, current: str) -> int:
ifnot self.is_unique(current):
return0 ans = len(current)
for i in range(start, len(arr)):
ans = max(ans, self.helper(arr, i +1, current + arr[i]))
return ans
defis_unique(self, s: str) -> bool:
return len(s) == len(set(s))
⏰ Time complexity: O(2^n * n), where n is the number of strings in the array. This is because we are generating all possible subsequences (which is 2^n) and for each subsequence, we are checking if the characters are unique (taking O(n) time in the worst case).
🧺 Space complexity: O(n), used by the recursion stack and to store unique characters for each subsequence.