Write a function to generate the generalized abbreviations of a word.
Note: The order of the output does not matter.
Example:
Input: "word"
Output:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
-------------------------------------------------------------------------------
The key for this problem is to remove duplicates:
set a number, arrange a character after the number, +some possibility in the following combinations:
class Solution:
def generateAbbreviations(self, word):
def dfs(w):
l,res = len(w),[w]
for last in range(l):
for first in range(last+1):
#[first:last+1]:num, [last+1,last+2]:ch, [last+2:]
for rest in dfs(w[last+2:]):
res.append(w[:first]+str(last-first+1)+w[last+1:last+2]+rest)
return res
ret = dfs(word)
return ret
s = Solution()
print(s.generateAbbreviations("word"))
Second solution, use binary:
class Solution:
def generateAbbreviations(self, word):
def get_abb(word, binary, l):
cnt = 0
res = ""
for i in range(l):
if (binary & (1 << (l-i-1))):
if (cnt > 0):
res += str(cnt)
res += word[i]
cnt = 0
else:
cnt += 1
if (cnt > 0):
res += str(cnt)
return res
res = []
lw = len(word)
for i in range(1<<lw):
res.append(get_abb(word, i, lw))
return res
s = Solution()
print(s.generateAbbreviations("word"))