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
| class Solution { public: unordered_set<unsigned long long> st; int P = 131, OFFSET = 128; vector<string> findAllConcatenatedWordsInADict(vector<string> &words) { for (auto &s : words) { unsigned long long hash = 0; for (auto &c : s) { hash = hash * P + (c - 'a') + OFFSET; } st.insert(hash); } vector<string> ans; for (auto &s : words) { if (check(s)) { ans.push_back(s); } } return ans; } bool check(string &s) { int n = s.size(); vector<int> f(n + 1, -1); f[0] = 0; for (int i = 0; i <= n; i++) { if (f[i] == -1) continue; unsigned long long cur = 0; for (int j = i + 1; j <= n; j++) { cur = cur * P + (s[j - 1] - 'a') + OFFSET; if (st.count(cur)) { f[j] = max(f[j], f[i] + 1); } } if (f[n] > 1) return true; } return false; } };
|