LeetCode1239. 串聯字符串的最大長度

1239. Maximum Length of a Concatenated String with Unique Characters

Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.

Return the maximum possible length of s.

Example 1:

Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.

Example 2:

Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".

Example 3:

Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26

Constraints:

  • 1 <= arr.length <= 16
  • 1 <= arr[i].length <= 26
  • arr[i] contains only lower case English letters.

題目:給定一個字符串數組 arr,字符串 s 是將 arr 某一子序列字符串連接所得的字符串,如果 s 中的每一個字符都只出現過一次,那麼它就是一個可行解。請返回所有可行解 s 中最長長度。

思路:DFS,組合問題。

工程代碼下載

【TLE】

class Solution {
public:
    int maxLength(vector<string>& arr) {
        int res = 0;
        helper(arr, "", res, 0);
        return res;
    }
private:
    void helper(const vector<string>& arr, string seen, int& res, int start){
        if(start == arr.size())
            return;

        for(int i = start; i < arr.size(); ++i){
            bool unique = true;

            // 判斷某個字符串中是否有重複的字符,"aaa"
            set<char> st(arr[i].begin(), arr[i].end());
            if(st.size() != arr[i].size())
                continue;

            // 判斷該字符串是否和seen中的字符串有重複的字符
            for(auto c : arr[i]){
                if(seen.find(c) != std::string::npos){
                    unique = false;
                    break;
                }
            }

            if(unique){
                helper(arr, seen+arr[i], res, i+1);
                res = max(res, (int)arr[i].size() + (int)seen.size());
            }
            else{
                helper(arr, seen, res, i+1);
            }
        }

        return;
    }
};

使用bitset,參考lee215

class Solution {
public:
    int maxLength(vector<string>& arr) {
        int res = 0;
        bitset<26> b;
        helper(arr, b, res, 0);
        return res;
    }
private:
    void helper(const vector<string>& arr, bitset<26> b, int& res, int start){
        if(start == arr.size())
            return;

        for(int i = start; i < arr.size(); ++i){
            bitset<26> a;
            string s = arr[i];
            for(auto c : s)
                a.set(c - 'a');

            int n = a.count();
            if(n != s.size())
                continue;

            if((a & b).any())
                helper(arr, b, res, i + 1);
            else
            {
                res = max(res, (int)b.count() + n);
                helper(arr, b | a, res, i + 1);
            }
        }

        return;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章