Python Solution O(N): Find Unique Characters


  • 0
    W

    Find unique character of that number and subtract its count. The order of subtraction matters. For example, after subtracting 'zero' and 'two', 'one' is the only number that has 'o' in it. Similar reasoning for other numbers.

    def originalDigits(self, s):
            """
            :type s: str
            :rtype: str
            """
            dic = collections.Counter(s)
            cnt = [0]*10
            
            cnt[0] = dic['z']
            for d in 'zero': dic[d] -= cnt[0]
            
            cnt[2] = dic['w']
            for d in 'two': dic[d] -= cnt[2]
            
            cnt[4] = dic['u']
            for d in 'four': dic[d] -= cnt[4]
            
            cnt[6] = dic['x']
            for d in 'six': dic[d] -= cnt[6]
            
            cnt[8] = dic['g']
            for d in 'eight': dic[d] -= cnt[8]
            
            cnt[1] = dic['o']
            for d in 'one': dic[d] -= cnt[1]
            
            cnt[3] = dic['r']
            for d in 'three': dic[d] -= cnt[3]
            
            cnt[5] = dic['f']
            for d in 'five': dic[d] -= cnt[5]
            
            cnt[7] = dic['v']
            for d in 'seven': dic[d] -= cnt[7]
            
            cnt[9] = dic['i']
            for d in 'nine': dic[d] -= cnt[9]
            
            res = ''
            for i, c in enumerate(cnt):
                res += str(i)*c
                
            return res
    

  • 0
    R

    @WKVictor Your solution is fast! But I do not understand how you can tell the number of digit in s by just count appears of unique letter, for example, you can "w" for 2 and "x" for 6, which is fine. But for 1, "o" is not unique, other digit also has this letter in their representation.


  • 0
    W

    @ruoyudocode The order matters. After subtracting 'zero' and 'one', 'two' is the only number that has 'o' in it. For other numbers, I did the same thing. That's how this solution works. Hope my answer helps.


  • 0
    R

    @WKVictor That is clever! Thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.