DEV Community

Discussion on: Daily Challenge #206 - Pound Means Backspace

Collapse
 
vidit1999 profile image
Vidit Sarkar

Here is a ugly Python one-liner using lambda.
Use Python 3.8

cleanString = lambda s,countPound=0 : ''.join(filter(lambda char : not isinstance(char, int), [(countPound := countPound + 1) if c == '#' else c if countPound == 0 else (countPound := countPound - 1) for c in s[::-1]]))[::-1]

print(cleanString("Thee# Empires# SS#tateBuildingg#")) # The Empire StateBuilding
print(cleanString("abc#d##c")) # ac
print(cleanString("abc#def##ghi###")) # abd
print(cleanString("abc##d######")) # empty string
print(cleanString("#######")) # empty string
print(cleanString("abc#de##c")) # abc
print(cleanString("abc####dhh##c#")) # d
print(cleanString("abcdef")) # abcdef
print(cleanString("########c")) # c

Idea is based on

def cleanString(s):
    countPound = 0
    ans = ""
    for c in s[::-1]:
        if c == '#':
            countPound += 1
        else:
            if countPound == 0:
                ans += c
            else:
                countPound -= 1
    return ans[::-1]