惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
G
Google Developers Blog
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
云风的 BLOG
云风的 BLOG
小众软件
小众软件
月光博客
月光博客
Recent Announcements
Recent Announcements
人人都是产品经理
人人都是产品经理
P
Proofpoint News Feed
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
The Cloudflare Blog
博客园_首页
美团技术团队
大猫的无限游戏
大猫的无限游戏
B
Blog
IT之家
IT之家
Jina AI
Jina AI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
Check Point Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - 北叶青藤

2096. Step-By-Step Directions From a Binary Tree Node to Another Find path from root to a target node in Binary Tree When Dijkstra Algorithm Should be Use? 1188. Design Bounded Blocking Queue 1115. Print FooBar Alternately 1114. Print in Order 1242. Web Crawler Multithreaded Python Multi-threading bot ip Log Rate Limiter Same Word of HTML Labels Most Frequent Call Chain 1102. Path With Maximum Minimum Value Property Booking Optimizer minimum number 755. Pour Water Keyword Tagging in Reviews with Overlapping Matches Retryer Function Implementation 1125. Smallest Sufficient Team Print the terrain Split stay Task scheduling problem 滑雪问题 845. Longest Mountain in Array 723. Candy Crush 1539. Kth Missing Positive Number 1650. Lowest Common Ancestor of a Binary Tree III 424. Longest Repeating Character Replacement 843. Guess the Word 551. Student Attendance Record I
remove prefix in a words list
北叶青藤 · 2026-04-06 · via 博客园 - 北叶青藤

Given a list of unique strings words. I needed to remove every string that was a prefix of any other string in the list.

A string a was a prefix of string b if b starts with a and the length of a was strictly less than the length of b.

My output contained only the strings from words that were not a prefix of any other string in the list, and I kept their relative order the same as in the original input list.

Constraints:

  • 1 ≤ words.length ≤ 10⁴

  • 1 ≤ words[i].length ≤ 100

  • Each words[i] consists of lowercase English letters, spaces, or printable characters.

  • All strings in words are distinct.

Example 1:

Input: words = ["a", "abc", "abc hello", "bc"] Output: ["abc hello", "bc"] Explanation:

  • "a" is a prefix of both "abc" and "abc hello", so it is removed.

  • "abc" is a prefix of "abc hello", so it is removed.

  • "abc hello" and "bc" are not prefixes of any other string.

Example 2:

Input: words = ["a", "ab", "abc"] Output: ["abc"]

 1 def remove_prefixes(words):
 2     if not words:
 3         return []
 4 
 5     # 1. Sort words lexicographically to bring prefixes next to their parents
 6     # This takes O(N log N * L) where L is max string length
 7     sorted_words = sorted(words)
 8     prefixes_to_remove = set()
 9 
10     for i in range(len(sorted_words) - 1):
11         current_word = sorted_words[i]
12         next_word = sorted_words[i+1]
13         
14         # 2. Check if the current word is a prefix of the next word
15         # .startswith() handles the prefix check efficiently
16         if next_word.startswith(current_word):
17             prefixes_to_remove.add(current_word)
18 
19     # 3. Filter the original list to maintain relative order
20     return [w for w in words if w not in prefixes_to_remove]
21 
22 # Example usage:
23 words1 = ["a", "abc", "abc hello", "bc"]
24 print(remove_prefixes(words1))  # Output: ["abc hello", "bc"]
25 
26 words2 = ["a", "ab", "abc"]
27 print(remove_prefixes(words2))  # Output: ["abc"]
 1 class TrieNode:
 2     def __init__(self):
 3         self.children = {}
 4         self.is_end = False
 5 
 6 class Trie:
 7     def __init__(self):
 8         self.root = TrieNode()
 9 
10     def insert(self, word):
11         node = self.root
12         for char in word:
13             if char not in node.children:
14                 node.children[char] = TrieNode()
15             node = node.children[char]
16         node.is_end = True
17 
18     def is_prefix_of_others(self, word):
19         node = self.root
20         for char in word:
21             node = node.children[char]
22         # If the node where the word ends has children, 
23         # it means this word is a prefix of a longer string.
24         return len(node.children) > 0
25 
26 def remove_prefixes_trie(words):
27     trie = Trie()
28     
29     # 1. Build the Trie
30     for word in words:
31         trie.insert(word)
32     
33     # 2. Filter words based on whether they have children in the Trie
34     # This maintains the original relative order
35     result = []
36     for word in words:
37         if not trie.is_prefix_of_others(word):
38             result.append(word)
39             
40     return result
41 
42 # Test
43 words = ["a", "abc", "abc hello", "bc"]
44 print(remove_prefixes_trie(words)) # Output: ["abc hello", "bc"]