Leetcode - 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.
Solution,#
λ©΄μ λ λͺ»νΌ λ¬Έμ (..). μ’ κ³ λ―ΌνλκΉ ν리긴 νλλ°, μμλ§ ν λ λ€μ νμ΄λ΄μΌκ² λ€. μ°μ , String μ νμ΄μ λ¬Έμλ‘ λ°κΏμΌ νλ€. Bitmask λ₯Ό μ¬μ©νλ©΄ μΆκ° 곡κ°μ ν¬κ² μ‘μλ¨Ήμ§ μλλ€.
- ASCII μ½λμμμ a
zλ 26κ°. Java μ int λ 32bit λΌμ μννΈ μ°μ°μΌλ‘ azλ₯Ό μ«μλ‘ λ³ν ν λ§μ€νΉνλ€ - μ λΆ λ§μ€νΉ ν 체ν¬λ₯Ό μμνλ€.
- μ§κΈ 보λ λ Έλλ³΄λ€ μ μ λ Έλλ λ³Ό νμκ° μλ€.
- νμ λ Έλλ λμΌν κ·μΉμ κ°μ§λ€.
class Solution {
public int maxLength(List<String> val) {
int[] arr = new int[val.size()];
for (int i = 0; i < val.size(); ++i) arr[i] = stringToBitmask(val.get(i));
return check(arr, 0, 0, 0);
}
private int stringToBitmask(String str) {
char[] arr = str.toCharArray();
int mask = 0;
for (char item : arr) {
if ((mask & (1 << item - 'a')) > 0) return 0;
mask += 1 << (item - 'a');
}
return mask;
}
private int check(int[] items, int me, int position, int max) {
for (int i = position; i < items.length; ++i) {
if ((me & items[i]) > 0) {
continue;
}
max = Math.max(max, check(items, me + items[i], i + 1, Math.max(max, Integer.bitCount(me + items[i]))));
}
return max;
}
}
Leetcode λ Runtimeμ΄ μ§λ§λλ‘λΌ λ―Ώμ μκ° μλ€(..)
λ°±νΈλνΉμ μ½ν΄μ λ νμ΄λ΄μΌκ² λ€. μ¬μ€ κ·Έλν νμ λ€ λͺ»νλνΈ.