zoukankan      html  css  js  c++  java
  • LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters

    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    In the arr, s could contain duplicate character. These strings with duplicate characters can't be used.

    Have a list to maintain all previous bit masks. When checking a new string s, check all previous bit masks, if there is not intersection, then s could be used.

    Update the maximum result and add the new bitmast into list.

    Time Complexity: expontential. 

    Space: expontential.

    AC Java:

     1 class Solution {
     2     public int maxLength(List<String> arr) {
     3         int res = 0;
     4         List<Integer> candidates = new ArrayList<>();
     5         candidates.add(0);
     6         
     7         for(String s : arr){
     8             int dup = 0;
     9             int sBit = 0;
    10             for(char c : s.toCharArray()){
    11                 dup |= sBit & 1<<(c-'a');
    12                 sBit |= 1<<(c-'a');
    13             }
    14             
    15             if(dup > 0){
    16                 continue;
    17             }
    18             
    19             for(int i = 0; i<candidates.size(); i++){
    20                 if((candidates.get(i) & sBit) > 0){
    21                     continue;
    22                 }
    23                 
    24                 candidates.add(candidates.get(i) | sBit);
    25                 res = Math.max(res, Integer.bitCount(candidates.get(i) | sBit));
    26             }
    27         }
    28         
    29         return res;
    30     }
    31 }
  • 相关阅读:
    创建型模式
    建造者模式
    抽象工厂模式
    工厂方法模式
    原型模式
    [水]三个日常签到题
    [数]青蛙的约会&Strange function
    [水]三个数学的小技巧题
    Jquery Ajax的使用
    easyui学习记录:combotree的使用
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11833971.html
Copyright © 2011-2022 走看看