[LeetCode] 1239. Maximum Length of a Concatenated String with Unique Characters
You are given an array of strings arr
. A string s
is formed by the concatenation of a subsequence of arr
that has unique characters.
Return the maximum possible length of s
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = ["un","iq","ue"] Output: 4 Explanation: All the valid concatenations are: - "" - "un" - "iq" - "ue" - "uniq" ("un" + "iq") - "ique" ("iq" + "ue") Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"] Output: 6 Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"] Output: 26 Explanation: The only string in arr has all 26 characters.
Constraints:
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i]
contains only lowercase English letters.
串联字符串的最大长度。
给定一个字符串数组 arr,字符串 s 是将 arr 的含有 不同字母 的 子序列 字符串 连接 所得的字符串。
请返回所有可行解 s 中最长长度。
子序列 是一种可以从另一个数组派生而来的数组,通过删除某些元素或不删除元素而不改变其余元素的顺序。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-length-of-a-concatenated-string-with-unique-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是 DFS backtracking。这里我用一个 letters 数组判断当前拼凑出来的 path 里面是否有重复字母,其他部分基本是标准的 DFS。
时间O(n*2^n)
空间O(n)
Java实现
1 class Solution { 2 int res = 0; 3 4 public int maxLength(List<String> arr) { 5 // corner case 6 if (arr == null || arr.size() == 0) { 7 return 0; 8 } 9 dfs(arr, "", 0); 10 return res; 11 } 12 13 private void dfs(List<String> arr, String path, int index) { 14 boolean isUnique = helper(path); 15 if (isUnique) { 16 res = Math.max(res, path.length()); 17 } 18 if (index == arr.size() || !isUnique) { 19 return; 20 } 21 for (int i = index; i < arr.size(); i++) { 22 dfs(arr, path + arr.get(i), i + 1); 23 } 24 } 25 26 private boolean helper(String s) { 27 boolean[] letters = new boolean[26]; 28 for (int i = 0; i < s.length(); i++) { 29 if (letters[s.charAt(i) - 'a'] == true) { 30 return false; 31 } 32 letters[s.charAt(i) - 'a'] = true; 33 } 34 return true; 35 } 36 }