1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| struct Trie { Trie* next[2]; bool eof = false; int mul = -1;
Trie() { memset(next, 0, sizeof next); }
void insert(int mask, int len, int pos = 27) { if(pos == -1) { eof = true; mul = max(mul, len); } else { bool bi = mask & (1<<pos); if(!next[bi]) next[bi] = new Trie(); next[bi]->insert(mask, len, pos - 1); } }
int query(int mask, int pos = 27) { if(pos == -1) return mul; int res = 0; bool bi = mask & (1<<pos); if(bi) { if(next[!bi]) res = next[!bi]->query(mask, pos - 1); } else { if(next[bi]) res = max(res, next[bi]->query(mask, pos - 1)); if(next[!bi]) res = max(res, next[!bi]->query(mask, pos - 1)); } return res; } }; class Solution { public: int maxProduct(vector<string>& words) { Trie* t = new Trie(); unordered_map<int, int> mp; int res = 0; for(auto& w : words) { int mask = 0; for(auto& ch : w) mask |= (1<<(ch-'a')); mp[mask] = max(mp[mask], (int)w.length()); } for(auto& [mask, count] : mp) { res = max(res, t->query(mask) * count); t->insert(mask, count); } return res; } };
|