Advertisement
kosievdmerwe

Untitled

Sep 22nd, 2021
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. class Solution:
  2.     def maxLength(self, arr: List[str]) -> int:
  3.         # Remove words with duplicate letters
  4.         arr = [s for s in arr if len(s) == len(set(s))]
  5.        
  6.         def to_letters_bitset(s: str) -> int:
  7.             ret = 0
  8.             for c in s:
  9.                 ret |= 1 << (ord(c) - ord('a'))
  10.             return ret
  11.         letters = [to_letters_bitset(s) for s in arr]
  12.        
  13.         ans = 0
  14.         comb = 1
  15.         MAX_COMB = 2 ** len(arr)
  16.         while comb < MAX_COMB:
  17.             comb_inc = 1
  18.            
  19.             cur_letters = 0
  20.             cur_len = 0
  21.             for i in range(len(arr) - 1, -1, -1):
  22.                 cur_bit = 2 ** i
  23.                 if (cur_bit & comb) == 0:
  24.                     continue
  25.                 if (cur_letters & letters[i]) != 0:
  26.                     comb -= comb & (cur_bit * 2 - 1)
  27.                     comb_inc = cur_bit * 2
  28.                     break
  29.                 cur_letters |= letters[i]
  30.                 cur_len += len(arr[i])
  31.             # We don't have to care if comb is valid as used_letters and
  32.             # cur_len are only increased when we have a valid prefix of comb
  33.             ans = max(ans, cur_len)
  34.             comb += comb_inc
  35.         return ans
  36.  
  37.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement