@@ -114,6 +114,111 @@ tags:
114114#### C++
115115
116116``` cpp
117+ class Solution {
118+ public:
119+ struct TrieNode {
120+ int count = 0;
121+ int depth = 0;
122+ int children[ 26] = {0};
123+ };
124+
125+ class SegmentTree {
126+ public:
127+ int n;
128+ vector<int> tree;
129+ vector<int>& globalCount;
130+ SegmentTree(int n, vector<int>& globalCount) : n(n), globalCount(globalCount) {
131+ tree.assign(4 * (n + 1), -1);
132+ build(1, 1, n);
133+ }
134+ void build (int idx, int l, int r) {
135+ if (l == r) {
136+ tree[ idx] = globalCount[ l] > 0 ? l : -1;
137+ return;
138+ }
139+ int mid = (l + r) / 2;
140+ build(idx * 2, l, mid);
141+ build(idx * 2 + 1, mid + 1, r);
142+ tree[ idx] = max(tree[ idx * 2] , tree[ idx * 2 + 1] );
143+ }
144+ void update(int idx, int l, int r, int pos, int newVal) {
145+ if (l == r) {
146+ tree[ idx] = newVal > 0 ? l : -1;
147+ return;
148+ }
149+ int mid = (l + r) / 2;
150+ if (pos <= mid)
151+ update(idx * 2, l, mid, pos, newVal);
152+ else
153+ update(idx * 2 + 1, mid + 1, r, pos, newVal);
154+ tree[ idx] = max(tree[ idx * 2] , tree[ idx * 2 + 1] );
155+ }
156+ int query() {
157+ return tree[ 1] ;
158+ }
159+ };
160+
161+ vector<int> longestCommonPrefix(vector<string>& words, int k) {
162+ int n = words.size();
163+ vector<int> ans(n, 0);
164+ if (n - 1 < k) return ans;
165+ vector<TrieNode> trie(1);
166+ for (const string& word : words) {
167+ int cur = 0;
168+ for (char c : word) {
169+ int idx = c - 'a';
170+ if (trie[cur].children[idx] == 0) {
171+ trie[cur].children[idx] = trie.size();
172+ trie.push_back({0, trie[cur].depth + 1});
173+ }
174+ cur = trie[cur].children[idx];
175+ trie[cur].count++;
176+ }
177+ }
178+ int maxDepth = 0;
179+ for (int i = 1; i < trie.size(); ++i) {
180+ if (trie[i].count >= k) {
181+ maxDepth = max(maxDepth, trie[i].depth);
182+ }
183+ }
184+ vector<int> globalCount(maxDepth + 1, 0);
185+ for (int i = 1; i < trie.size(); ++i) {
186+ if (trie[i].count >= k && trie[i].depth <= maxDepth) {
187+ globalCount[trie[i].depth]++;
188+ }
189+ }
190+ vector<vector<int>> fragileList(n);
191+ for (int i = 0; i < n; ++i) {
192+ int cur = 0;
193+ for (char c : words[i]) {
194+ int idx = c - 'a';
195+ cur = trie[cur].children[idx];
196+ if (trie[cur].count == k) {
197+ fragileList[i].push_back(trie[cur].depth);
198+ }
199+ }
200+ }
201+ int segSize = maxDepth;
202+ if (segSize >= 1) {
203+ SegmentTree segTree(segSize, globalCount);
204+ for (int i = 0; i < n; ++i) {
205+ if (n - 1 < k) {
206+ ans[i] = 0;
207+ } else {
208+ for (int d : fragileList[i]) {
209+ segTree.update(1, 1, segSize, d, globalCount[d] - 1);
210+ }
211+ int res = segTree.query();
212+ ans[i] = res == -1 ? 0 : res;
213+ for (int d : fragileList[i]) {
214+ segTree.update(1, 1, segSize, d, globalCount[d]);
215+ }
216+ }
217+ }
218+ }
219+ return ans;
220+ }
221+ };
117222
118223```
119224
0 commit comments