|
1 | 1 | package main
|
| 2 | + |
| 3 | +func maxLength(arr []string) int { |
| 4 | + st := make([]int, 0, len(arr)) |
| 5 | + for i := range arr { |
| 6 | + s := 0 |
| 7 | + f := true |
| 8 | + for j := range arr[i] { |
| 9 | + b := 1 << (arr[i][j] - 97) |
| 10 | + if b&s != 0 { |
| 11 | + f = false |
| 12 | + break |
| 13 | + } |
| 14 | + s |= b |
| 15 | + } |
| 16 | + if f { |
| 17 | + st = append(st, s) |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + r := -1 |
| 22 | + var f func(int, int) |
| 23 | + f = func(i, s int) { |
| 24 | + cnt := 0 |
| 25 | + ds := s |
| 26 | + for ds > 0 { |
| 27 | + cnt += ds & 1 |
| 28 | + ds = ds >> 1 |
| 29 | + } |
| 30 | + if cnt > r { |
| 31 | + r = cnt |
| 32 | + } |
| 33 | + if i >= len(st) { |
| 34 | + return |
| 35 | + } |
| 36 | + for j := i + 1; j < len(st); j++ { |
| 37 | + if s&st[j] == 0 { |
| 38 | + f(j, s|st[j]) |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + f(-1, 0) |
| 43 | + return r |
| 44 | +} |
| 45 | + |
| 46 | +/* |
| 47 | +
|
| 48 | +
|
| 49 | +
|
| 50 | +func maxLength(arr []string) int { |
| 51 | + masks := make([]int, len(arr)) |
| 52 | + for i, s := range arr { |
| 53 | + masks[i] = createMask(s) |
| 54 | + } |
| 55 | +
|
| 56 | + maxLen := 0 |
| 57 | + for i := 0; i < len(arr); i++ { |
| 58 | + maxLen = max(maxLen, dp(arr, masks, 0, 0, map[int]int{})) |
| 59 | + } |
| 60 | +
|
| 61 | + return maxLen |
| 62 | +} |
| 63 | +
|
| 64 | +func dp(arr []string, masks []int, curMask int, pos int, memo map[int]int) int { |
| 65 | + if pos == len(arr) { |
| 66 | + return 0 |
| 67 | + } |
| 68 | + memoKey := (curMask << 32) | pos |
| 69 | + if memo[memoKey] > 0 { |
| 70 | + return memo[memoKey] |
| 71 | + } |
| 72 | + maxLen := dp(arr, masks, curMask, pos + 1, memo) // ignoring arr[pos] word |
| 73 | + if masks[pos] != 0 && (curMask & masks[pos]) == 0 { |
| 74 | + maxLen = max( |
| 75 | + maxLen, |
| 76 | + len(arr[pos]) + dp(arr, masks, curMask | masks[pos], pos + 1, memo), |
| 77 | + ) |
| 78 | + } |
| 79 | + memo[memoKey] = maxLen |
| 80 | + return maxLen |
| 81 | +} |
| 82 | +
|
| 83 | +func createMask(s string) int { |
| 84 | + mask := 0 |
| 85 | + for _, b := range s { |
| 86 | + add := 1 << (b - 'a') |
| 87 | + if (mask & add) == add { |
| 88 | + return 0 // duplicate byte (char) |
| 89 | + } |
| 90 | + mask |= add |
| 91 | + } |
| 92 | + return mask |
| 93 | +} |
| 94 | +
|
| 95 | +func max(a, b int) int { |
| 96 | + if a > b { |
| 97 | + return a |
| 98 | + } |
| 99 | + return b |
| 100 | +} |
| 101 | +
|
| 102 | +
|
| 103 | +
|
| 104 | +*/ |
0 commit comments