JavaScript O(n) solution


  • 1
    var originalDigits = function(s) {
        const words = { 'z': 'zero', 'x': 'six', 'w': 'two', 'u': 'four', 'g': 'eight', 's': 'seven', 'v': 'five', 'r': 'three', 'o': 'one', 'n': 'nine' };
        const nums = { 'z': 0, 'x': 6, 'w': 2, 'u': 4, 'g': 8, 's': 7, 'v': 5, 'r': 3, 'o': 1, 'n': 9 };
        let order = 'zxwugsvron';
        const counts = {};
        for (let c of s) {
            counts[c] = (counts[c] || 0) + 1;
        }
        const res = new Array(10);
        for (let key of order) {
            while (counts[key]) {
                for (let w of words[key]) {
                    counts[w]--;
                }
                res[nums[key]] = (res[nums[key]] || '') + nums[key];
            }
        }
        return res.join('');
    };
    

    Not particularly fast on the OJ histogram but does the job in linear time and space.


Log in to reply
 

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