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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值