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

推荐订阅源

V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
罗磊的独立博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
T
Tailwind CSS Blog
美团技术团队
Y
Y Combinator Blog
I
InfoQ
C
Check Point Blog
Microsoft Security Blog
Microsoft Security Blog
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
博客园 - Franky
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
爱范儿
爱范儿
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
A
Arctic Wolf
Hugging Face - Blog
Hugging Face - Blog
S
Security Affairs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
云风的 BLOG
云风的 BLOG
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Announcements
Recent Announcements
H
Heimdal Security Blog
博客园 - 司徒正美
Latest news
Latest news
H
Hacker News: Front Page
H
Help Net Security
Know Your Adversary
Know Your Adversary
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Secure Thoughts
AWS News Blog
AWS News Blog
V
Vulnerabilities – Threatpost
NISL@THU
NISL@THU
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LangChain Blog
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
The Cloudflare Blog
I
Intezer
N
News and Events Feed by Topic

博客园 - 北叶青藤

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"]