Reconstruct Original Digits from English

Problem Id: 423 Difficulty: Medium


Intuition

Solution


class Solution:
    def originalDigits(self, s: str) -> str:
        eng = ['zero', 'one', 'two', 'three', 'four', 'five',
               'six', 'seven', 'eight', 'nine']
        counts = {c: s.count(c) for c in string.ascii_lowercase}
        digits = [0] * 10

        # Direct numbers
        digits[0] = counts['z']
        digits[2] = counts['w']
        digits[4] = counts['u']
        digits[6] = counts['x']
        digits[8] = counts['g']
        for num in (0, 2, 4, 6, 8):
            for c in eng[num]:
                counts[c] -= digits[num]

        # Second-direct numbers
        digits[1] = counts['o']
        digits[3] = counts['t']
        digits[5] = counts['f']
        digits[7] = counts['s']
        digits[9] = counts['i'] - digits[5]
        ans = ''.join(str(num) * digits[num] for num in range(10) if digits[num])
        return ans