Leetcode 1239. 串聯字符串的最大長度

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

給定一個字符串數組 arr,字符串 s 是將 arr 某一子序列字符串鏈接所得的字符串,若是 s 中的每個字符都只出現過一次,那麼它就是一個可行解。優化

請返回全部可行解 s 中最長長度。spa

 

示例 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
 

 

提示:code

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

 

題解:leetcode

1 首先考慮DFS 遍歷各類組合 字符串

2 考慮使用bit表明各個字符出現與否get

  這裏爲了代碼寫的方便 使用了一個26長度的數組 記錄字符是否出現與否string

代碼hash

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;
}

};
相關文章
相關標籤/搜索