Software Enginner πŸ‡―πŸ‡΅ and πŸ‡°πŸ‡·

Leetcode - Maximum Length of a Concatenated String with Unique Characters

Problem Maximum Length of a Concatenated String with Unique Characters
Difficulty Medium
Language Java
Time complexity $$O(2^n)$$
Space complexity $$O(n)$$

Problem,

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 λ₯Ό μ‚¬μš©ν•˜λ©΄ μΆ”κ°€ 곡간을 크게 μž‘μ•„λ¨Ήμ§€ μ•ŠλŠ”λ‹€.

  1. ASCII μ½”λ“œμƒμ—μ„œ a~zλŠ” 26개. Java 의 int λŠ” 32bit λΌμ„œ μ‹œν”„νŠΈ μ—°μ‚°μœΌλ‘œ a~zλ₯Ό 숫자둜 λ³€ν™˜ ν›„ λ§ˆμŠ€ν‚Ήν•œλ‹€
  2. μ „λΆ€ λ§ˆμŠ€ν‚Ή ν›„ 체크λ₯Ό μ‹œμž‘ν•œλ‹€.
  3. μ§€κΈˆ λ³΄λŠ” λ…Έλ“œλ³΄λ‹€ μ „μ˜ λ…Έλ“œλŠ” λ³Ό ν•„μš”κ°€ μ—†λ‹€.
  4. ν•˜μœ„ λ…Έλ“œλ„ λ™μΌν•œ κ·œμΉ™μ„ 가진닀.
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

Leetcode λŠ” Runtime이 μ§€λ§˜λŒ€λ‘œλΌ 믿을 μˆ˜κ°€ μ—†λ‹€(..)

λ°±νŠΈλž˜ν‚Ήμ— μ•½ν•΄μ„œ 더 풀어봐야겠닀. 사싀 κ·Έλž˜ν”„ 탐색 λ‹€ λͺ»ν•˜λŠ”νŽΈ.