423 Reconstruct Original Digits from English
Given a non-empty string containing an out-of-order English representation of digits 0-9
, output the digits in ascending order.
Note:
Input contains only lowercase English letters.
Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
Input length is less than 50,000.
Example 1:
Example 2:
The Idea: You can get really creative with this problem. This following approach beats 100% of python3 submissions. This idea goes as follows. First identify groups that can uniquely identify a character in the string. In the first group, we can use z, w, u, x, and g to uniquely identify numbers 0, 2, 4, 6, and 8. The remaining characters are ambiguous, so we create a second group. This group assumes that all the occurrences of the first group are gone. It is only when the first group of numbers are gone that we can uniquely identify the next group of numbers. We find that o, r, f, and s can be used to uniquely identify 1, 3, 5, and 7. Repeat the same idea for the last group. Now run the string through a counter to get a distribution of the string. Through a single iteration of all 3 groups, we should be able to identify all the numbers.
Complexity: O(n + nlogn) time and O(1) space
Last updated