donnemartin / interactive-coding-challenges

120+ interactive Python coding interview challenges (algorithms and data structures). Includes Anki flashcards.
Other
29.57k stars 4.46k forks source link

string compression solutions don't match description #271

Open cristianmtr opened 4 years ago

cristianmtr commented 4 years ago

Hello

In the string compression challenge:

        assert_equal(func('AAABCCDDDDE'), 'A3BC2D4E')
        assert_equal(func('BAAACCDDDD'), 'BA3C2D4')
        assert_equal(func('AAABAACCDDDD'), 'A3BA2C2D4')

The C2 doesn't save space, right? Shouldn't it be just CC ?

amitShindeGit commented 4 years ago

What could we do here then to save space? I'd really like to know.

adarsh-tyagi commented 3 years ago

Alphabets count should be taken only when they are recurring more than 2 times. Let's say we have string AAABCCD, in this string A occurs thrice then it will be A3, B and D are single so they will be taken as it is. But in case of C, count should be taken if it is ocurring more than twice. In this case it should be CC but when it is more than 2 suppose CCC then the count should be taken. We can do this by below method.

` s = "AAABCCDDDDE" output = '' hashMap = {} for i in range(0, len(s)): if s[i] not in hashMap: hashMap[s[i]] = 1 else: hashMap[s[i]] += 1

for key, value in hashMap.items(): if value > 2: output += str(key)+str(value) else: output += str(key)*value

print(output) `