Word Abbreviation — LeetCode 527 Python Solution
- Problem
- #527
- Pattern
- Trie
- Reading time
- 7 min
- Source
- leetcode.com
The problem
Given an array of distinct strings words, return the minimal possible abbreviations for every word. The following are the rules for a string abbreviation: The initial abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.
Example
- Input
- words = ["like","god","internal","me","internet","interval","intension","face","intrusion"]
- Output
- ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]
Python solution
class Trie:
__slots__ = ["children", "cnt"]
def __init__(self):
self.children = [None] * 26
self.cnt = 0
def insert(self, w: str):
node = self
for c in w:
idx = ord(c) - ord("a")
if not node.children[idx]:
node.children[idx] = Trie()
node = node.children[idx]
node.cnt += 1
def search(self, w: str) -> int:
node = self
cnt = 0
for c in w:
cnt += 1
idx = ord(c) - ord("a")
node = node.children[idx]
if node.cnt == 1:
return cnt
return len(w)
class Solution:
def wordsAbbreviation(self, words: List[str]) -> List[str]:
tries = {}
for w in words:
m = len(w)
if (m, w[-1]) not in tries:
tries[(m, w[-1])] = Trie()
tries[(m, w[-1])].insert(w)
ans = []
for w in words:
cnt = tries[(len(w), w[-1])].search(w)
ans.append(
w if cnt + 2 >= len(w) else w[:cnt] + str(len(w) - cnt - 1) + w[-1]
)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(L) |
| Space | O(L) auxiliary |
Pattern: Trie
Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 527. Word Abbreviation is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.
The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 527. Word Abbreviation?
- LeetCode 527. Word Abbreviation is rated Hard on LeetCode.
- What is the time complexity of LeetCode 527. Word Abbreviation?
- The Python solution on this page runs in O(L).
- What is the space complexity of LeetCode 527. Word Abbreviation?
- The Python solution on this page uses O(L) auxiliary space.
- What topics does LeetCode 527. Word Abbreviation cover?
- LeetCode 527. Word Abbreviation is tagged Greedy, Trie, Array, String and Sorting on LeetCode.
- Is LeetCode 527. Word Abbreviation a premium problem?
- Yes. LeetCode 527. Word Abbreviation is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.