Tuesday, October 31, 2017

423. Reconstruct Original Digits from English

https://leetcode.com/problems/reconstruct-original-digits-from-english/description/
Solution 1. no need to sort. (19 ms)
    string originalDigits(string s) {
        string res;
        vector<string> ns = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        // order to check the numbers
        vector<int> order = {0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
        // distinct char of each number
        vector<char> orderc = {'z', 'w', 'u', 'x', 'g', 'o', 'r', 'f', 'v', 'i'};
        vector<int> m(256,0);
        vector<string> part(10,"");
        for(char& c: s) m[c]++;
        for(int i=0; i<10; i++) {
            int n = order[i];
            char key = orderc[i];
            int cnt = m[key];  // count to be remove for each char in a word
            for(char& c : ns[n]) m[c] -= cnt;
            part[n] = string(cnt, char('0' + n));

        }
        for(string& p : part) res += p;
        return res;
    }
or,
    string originalDigits(string s) {
        string res;
        vector<string> ns = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        vector<int> order = {0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
        vector<char> orderc = {'z', 'w', 'u', 'x', 'g', 'o', 'r', 'f', 'v', 'i'};
        vector<int> m(256,0);
        for(char& c: s) m[c]++;
        for(int i=0; i<10; i++) {
            int n = order[i];
            char key = orderc[i];
            while(m[key] > 0) {
                for(char& c : ns[n]) m[c]--;
                res += to_string(n);
            }
        }
        sort(res.begin(), res.end());
        return res;
    }

No comments:

Post a Comment