423. Reconstruct Original Digits from English

Description

Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.

Note:

  1. Input contains only lowercase English letters.

  2. 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.

  3. Input length is less than 50,000.

Constraints

Approach

Examples

Input: "owoztneoer"

Output: "012"

Solutions

/**
 * Time complexity : O(N)
 * Space complexity : O(1)
 */

class Solution {
    public String originalDigits(String s) {
        int sLen = s.length();
        int[] count = new int[10];
        
        for(int i = 0; i < sLen; i++) {
            char ch = s.charAt(i);
            if(ch == 'z') count[0]++;
            else if(ch == 'o') count[1]++;
            else if(ch == 'w') count[2]++;
            else if(ch == 'h') count[3]++;
            else if(ch == 'u') count[4]++;
            else if(ch == 'f') count[5]++;
            else if(ch == 'x') count[6]++;
            else if(ch == 's') count[7]++;
            else if(ch == 'g') count[8]++;
            else if(ch == 'i') count[9]++;
        }
        
        count[1] -= (count[0] + count[2] + count[4]);
        count[3] -= count[8];
        count[5] -= count[4];
        count[7] -= count[6];
        count[9] -= (count[5] + count[6] + count[8]);
        
        StringBuilder resultSB = new StringBuilder();
        for(int i = 0; i < count.length; i++) {
            while(count[i]-- > 0) {
                resultSB.append(i);
            }
        }
        
        return resultSB.toString();
    }
}

Follow up

Last updated

Was this helpful?