LC 0320 [M] Generalized Abbreviation - ALawliet/algorithms GitHub Wiki
class Solution:
def generateAbbreviations(self, word: str) -> List[str]:
def abbreviate(path):
res = ''
count = 0
for x in path:
if x == '_':
count += 1
elif x.isalpha(): # abbreviation _ and letter cannot be adjacent so if else works
if count:
res += str(count)
count = 0
res += x
# one more for last char is count with no letters remaining
if count:
res += str(count)
return res
def dfs(i, path):
if i == len(word):
res.append(abbreviate(path))
else:
dfs(i + 1, path + word[i])
dfs(i + 1, path + '_')
res = []
dfs(0, '')
return res
class Solution(object):
def generateAbbreviations(self, word):
def helper(idx, soFar, count):
if idx == len(word):
# Once we reach the end, append current to the result
coll.append(soFar + (str(count) if count > 0 else soFar))
else:
# Skip current position, and increment count
helper(idx + 1, soFar, count + 1)
# Include current position, and zero-out count
helper(idx + 1, soFar + (str(count) if count > 0 else '') + word[idx], 0)
coll = []
helper(0, '', 0)
return coll
class Solution:
def generateAbbreviations(self, word: str) -> List[str]:
def abbreviate(soFar):
res = ''
count = 0
for i in soFar:
if i == '_':
count += 1
else:
if count > 0:
res += str(count)
count = 0
res += i
if count:
res += str(count)
return res
def helper(idx, soFar):
if idx == len(word):
coll.append(abbreviate(soFar))
return
helper(idx + 1, soFar + word[idx])
helper(idx + 1, soFar + '_')
coll = []
helper(0, '')
return coll