[leetcode 周賽 160] 1239 串聯字符串的最大長度


1239 Maximum Length of a Concatenated String with Unique Characters 串聯字符串的最大長度

問題描述

給定一個字符串數組 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] 中只含有小寫英文字母

思路

  • 讀題
    題目需要的字符串是一個沒有重復字符的字符串, 所提供的字符串數組, 可以進行拼接, 得到最長的那個沒有重復字符的字符串.

回溯法(遞歸)+DFS剪枝

分析算法規模: 遞歸深度最多16層, 運算規模最大2^17(回溯樹上節點)
遍歷所有可能的解, 嘗試不同字符串的組合(回溯)
回溯法

代碼實現

回溯法(遞歸)+DFS剪枝

class Solution {
    private int ans = 0;

    public int maxLength(List<String> arr) {
        if (arr == null) {
            return 0;
        }

        // 遍歷整個字符串數組 獲得符合條件的單個字符串最大長度
        for (String ar : arr) {
            if (nonDuplicate(ar)) {
                ans = Math.max(ar.length(), ans);
            }
        }
        // DFS 從0開始 初始字符串為空串
        helper(arr, 0, "");

        return ans;
    }

    private void helper(List<String> arr, int idx, String prev) {
        // 剪枝 沒有重復(符合條件)才可以繼續往下走
        if (nonDuplicate(prev)) {
            ans = Math.max(prev.length(), ans);
        } else {
            return;
        }

        // 最后一個節點 返回
        if (idx > arr.size()) {
            return;
        }
        // 當前字符串
        String cur = arr.get(idx);
        // 添加
        helper(arr, idx + 1, prev + cur);
        // 不添加
        helper(arr, idx + 1, prev);
    }

    private boolean nonDuplicate(String str) {
        return str.chars().distinct().count() == str.length();
    }
}

參考資源

第 160 場周賽 全球排名


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM