【LeetCode 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.

思路

DFS,int数字表示当前字符串中是否有26个字母的状态。

代码

class Solution {
public:
    int maxLength(vector<string>& arr) {
        dfs(arr, 0, 0, "");
        return ans;
    }
    
private:
    int ans = 0;
    void dfs(vector<string>& arr, int cnt, int status, string cur) {
        if (cnt == arr.size()) {
            int len = cur.length();
            ans = max(ans, len);
            return;
        }
        string str = arr[cnt];
        bool flag = true;
        int ns = status;
        for (const auto& ch: str) {
            if ((status & (1<<(ch-'a'))) != 0) {
                flag = false;
                break;
            }
            status |= (1<<(ch-'a'));
        }
        if (flag) dfs(arr, cnt+1, status, cur+str);
        dfs(arr, cnt+1, ns, cur);
        return;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值