Leetcode 1239. 串联字符串的最大长度

地址 https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/submissions/

给定一个字符串数组 arr,字符串 s 是将 arr 某一子序列字符串连接所得的字符串,如果 s 中的每一个字符都只出现过一次,那么它就是一个可行解。

请返回所有可行解 s 中最长长度。

 

复制代码
示例 1:

输入:arr = ["un","iq","ue"]
输出:4
解释:所有可能的串联组合是 "","un","iq","ue","uniq""ique",最大长度为 4。
示例 2:

输入:arr = ["cha","r","act","ers"]
输出:6
解释:可能的解答有 "chaers""acters"。
示例 3:

输入:arr = ["abcdefghijklmnopqrstuvwxyz"]
输出:26
 
复制代码

 

提示:

1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i] 中只含有小写英文字母

 

题解:

1 首先考虑DFS 遍历各种组合 

2 考虑使用bit代表各个字符出现与否

  这里为了代码写的方便 使用了一个26长度的数组 记录字符是否出现与否

代码

复制代码
class Solution {
public:
    vector<int>  currenthash;
int currentLen;
vector<vector<int>> hashVec;
int ret = -9999;

bool CheckHash(vector<int>& hash1, vector<int>& hash2) {
    for (int i = 0; i < hash1.size(); i++) {
        if (hash1[i] + hash2[i] > 1)
            return false;
    }

    return true;
}

void startTry(int idx,int currentLen, vector<string>& arr)
{
    if (idx == arr.size()) {
        ret = max(ret, currentLen);
        return;
    }

    if (CheckHash(currenthash, hashVec[idx])) {
        currentLen += arr[idx].size();
        for (int i = 0; i < currenthash.size(); i++) {
            currenthash[i] += hashVec[idx][i];
        }
        startTry(idx + 1, currentLen,arr);
        for (int i = 0; i < currenthash.size(); i++) {
            currenthash[i] -= hashVec[idx][i];
        }
        currentLen -= arr[idx].size();
    }
    startTry(idx + 1, currentLen, arr);

}

int maxLength(vector<string>& arr) {
    currenthash = vector<int>(26, 0);
    currentLen = 0;
    hashVec = vector<vector<int>>(arr.size(), vector<int>(26, 0));

    for (int i = 0; i < arr.size(); i++) {
        for (int j = 0; j < arr[i].size(); j++) {
            int idx = arr[i][j] - 'a';
            hashVec[i][idx]++;
            //优化
        }
    }

    currenthash = vector<int>(26, 0);
    currentLen = 0;
    startTry(0, 0,arr);
    return ret;
}

};
复制代码

 

posted on   itdef  阅读(904)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示