• [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.

    串联字符串的最大长度。

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

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是DFS backtracking。这里我用一个 letters 数组判断当前拼凑出来的 path 里面是否有重复字母,其他部分基本是标准的DFS。

    时间O(n*2^n)

    空间O(n)

    Java实现

     1 class Solution {
     2     int res = 0;
     3 
     4     public int maxLength(List<String> arr) {
     5         // corner case
     6         if (arr == null || arr.size() == 0) {
     7             return 0;
     8         }
     9         dfs(arr, "", 0);
    10         return res;
    11     }
    12 
    13     private void dfs(List<String> arr, String path, int index) {
    14         boolean isUnique = helper(path);
    15         if (isUnique) {
    16             res = Math.max(res, path.length());
    17         }
    18         if (index == arr.size() || !isUnique) {
    19             return;
    20         }
    21         for (int i = index; i < arr.size(); i++) {
    22             dfs(arr, path + arr.get(i), i + 1);
    23         }
    24     }
    25 
    26     private boolean helper(String s) {
    27         boolean[] letters = new boolean[26];
    28         for (int i = 0; i < s.length(); i++) {
    29             if (letters[s.charAt(i) - 'a'] == true) {
    30                 return false;
    31             }
    32             letters[s.charAt(i) - 'a'] = true;
    33         }
    34         return true;
    35     }
    36 }

    LeetCode 题目总结

  • 相关阅读:
    C#网络编程TCP通信实例程序简单设计
    C#网络编程TCP通信实例程序简单设计
    2329: 密码破解【数组】
    纸牌游戏小猫钓鱼
    认识栈
    认识队列
    2754: C++习题快速排序
    3047: 快速排序算法
    Problem A: C语言习题 链表建立,插入,删除,输出
    Problem C: 动态规划基础题目之数字三角形
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14905847.html
Copyright © 2020-2023  润新知