Cracking The Code Interview CH1.6


In [6]:
# Input
s = 'aabcccccaaa'
# Desired Output
output = 'a2b1c5a3'

In [2]:
# Method1 - Use a new list
def string_compression(s):
    l = []
    count = 0
    
    for i in range(len(s)):
        if i == 0:
            l.append(s[i])
            count = 1

        else:
            if s[i] == s[i-1]:
                count += 1
            else:
                l.append(str(count))
                l.append(s[i])
                count = 1
    l.append(str(count))
    result = "".join(l)
    return result

In [3]:
string_compression(s)


Out[3]:
'a2b1c5a3'

In [4]:
# Method2 - Use string directly
def string_compression1(s):
    new_s = ''
    count = 0
    
    for i in range(len(s)):
        if i == 0:
            new_s += s[i]
            count = 1

        else:
            if s[i] == s[i-1]:
                count += 1
            else:
                new_s += str(count)
                new_s += s[i]
                count = 1
    new_s += str(count)
    return new_s

In [5]:
string_compression1(s)


Out[5]:
'a2b1c5a3'