Python Solution Beats 100%

  • 0

    Here's how this works:

    Go through all the digits from "zero" to "nine", and find a unique character in each that no other digits have. So, for "zero", no other digits have a "z" so you can tell how many "zero"s there are in the string. For "one", there are no unique characters so skip this (we'll get back to this later). For "two", the unique character would be "w"... and so on

    Now that you know the number of first pass digits, neglect the first pass digits, do a second pass and find the unique characters that no other remaining digit has. Here, you can count the number of second pass digits in the event that you theoretically removed the first pass digits from the string... Continue on like so.

    Now, lets take a second pass digit like 5. You can get a count of 5 because you know the count of the first pass digit 4. How? "f" only occurs in both 4 and 5. You know the number of 4s in the string because its in your first pass (count the number of "u"s in the string). So all you have to do, is count the number of "f"s in the string, and calculate number of 5s equals number of "f"s - number of 4s.

    Yadda yadda, the rest of this code should be straightforward.

        def originalDigits(self, s):
            :type s: str
            :rtype: str
            digits = [0] * 10
            # first pass digits
            digits[0] = s.count('z')
            digits[2] = s.count('w')
            digits[4] = s.count('u')
            digits[6] = s.count('x')
            digits[8] = s.count('g')
            # second pass digits
            digits[1] = s.count('o') - digits[0] - digits[2] - digits[4]
            digits[3] = s.count('h') - digits[8]
            digits[5] = s.count('f') - digits[4]
            digits[7] = s.count('s') - digits[6]
            # third pass digit
            digits[9] = s.count('i') - digits[5] - digits[6] - digits[8]
            number = ""
            for index in xrange(len(digits)):
                count = digits[index]
                if count > 0:
                    number += count*str(index)
            return number

Log in to reply

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