Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f8619c8

Browse files
Generalized Abbreviation
1 parent 25ae478 commit f8619c8

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'''Leetcode- https://leetcode.com/problems/generalized-abbreviation/ '''
2+
'''
3+
A word's generalized abbreviation can be constructed by taking any number of non-overlapping and non-adjacent substrings and replacing them with their respective lengths.
4+
5+
For example, "abcde" can be abbreviated into:
6+
"a3e" ("bcd" turned into "3")
7+
"1bcd1" ("a" and "e" both turned into "1")
8+
"5" ("abcde" turned into "5")
9+
"abcde" (no substrings replaced)
10+
However, these abbreviations are invalid:
11+
"23" ("ab" turned into "2" and "cde" turned into "3") is invalid as the substrings chosen are adjacent.
12+
"22de" ("ab" turned into "2" and "bc" turned into "2") is invalid as the substring chosen overlap.
13+
Given a string word, return a list of all the possible generalized abbreviations of word. Return the answer in any order.
14+
15+
Example 1:
16+
17+
Input: word = "word"
18+
Output: ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
19+
20+
'''
21+
22+
def generateAbbreviations(word):
23+
res = []
24+
25+
def backtrack(i,cur):
26+
if i == len(word):
27+
res.append("".join(cur))
28+
return
29+
30+
cur.append(word[i])
31+
backtrack(i+1,cur)
32+
cur.pop()
33+
34+
if not cur or not cur[-1][-1].isdigit():
35+
for j in range(1,len(word)-i+1):
36+
cur.append(str(j))
37+
backtrack(i+j,cur)
38+
cur.pop()
39+
40+
backtrack(0,[])
41+
return res
42+
43+
#T: O(n.2^n)
44+
#S:O(n)

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,6 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1919
- [x] [Generate Parentheses](Backtracking/22-Generate-Parentheses.py)
2020
- [x] [Palindrome Partitioning](Backtracking/131-Palindrome-Partitioning.py)
2121
- [x] [Letter Combinations of a Phone Number](Backtracking/17-Letter-Combinations-of-a-Phone-Number.py)
22+
- [x] [Generalized Abbreviation](Backtracking/320-Generalized-Abbreviation.py)
2223

2324

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /