1. 程式人生 > >[LeetCode] Reconstruct Original Digits from English 從英文中重建數字

[LeetCode] 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:

  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.

Example 1:

Input: "owoztneoer"

Output: "012"

Example 2:

Input: "fviefuro"

Output: "45"

這道題給了我們一串英文字串,是由表示數字的英文單片語成的,不過字元順序是打亂的,讓我們重建出數字。那麼這道題的思路是先要統計出各個字元出現的次數,然後算出每個單詞出現的次數,然後就可以重建了。由於題目中限定了輸入的字串一定是有效的,那麼不會出現無法成功重建的情況,這裡需要用個trick。我們仔細觀察這些表示數字的單詞"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",我們可以發現有些的單詞的字元是獨一無二的,比如z,只出現在zero中,還有w,u,x,g這四個單詞,分別只出現在two,four,six,eight中,那麼這五個數字的個數就可以被確定了,由於含有o的單詞有zero,two,four,one,其中前三個都被確定了,那麼one的個數也就知道了;由於含有h的單詞有eight,three,其中eight個數已知,那麼three的個數就知道了;由於含有f的單詞有four,five,其中four個數已知,那麼five的個數就知道了;由於含有s的單詞有six,seven,其中six個數已知,那麼seven的個數就知道了;由於含有i的單詞有six,eight,five,nine,其中前三個都被確定了,那麼nine的個數就知道了,知道了這些問題就變的容易多了,我們按這個順序"zero", "two", "four", "six", "eight", "one", "three", "five", "seven", "nine"就能找出所有的個數了,參見程式碼如下:

解法一:

class Solution {
public:
    string originalDigits(string s) {
        string res = "";
        vector<string> words{"zero", "two", "four", "six", "eight", "one", "three", "five", "seven", "nine"};
        vector<int> nums{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}, counts(26, 0);
        vector
<char> chars{'z', 'w', 'u', 'x', 'g', 'o', 'h', 'f', 's', 'i'}; for (char c : s) ++counts[c - 'a']; for (int i = 0; i < 10; ++i) { int cnt = counts[chars[i] - 'a']; for (int j = 0; j < words[i].size(); ++j) { counts[words[i][j] - 'a'] -= cnt; } while (cnt--) res += (nums[i] + '0'); } sort(res.begin(), res.end()); return res; } };

另外我們也可以用更加簡潔易懂的方法來快速的找出各個數字的個數,參見程式碼如下:

解法二:

class Solution {
public:
    string originalDigits(string s) {
        string res = "";
        vector<int> counts(128, 0), nums(10, 0);
        for (char c : s) ++counts[c];
        nums[0] = counts['z'];
        nums[2] = counts['w'];
        nums[4] = counts['u'];
        nums[6] = counts['x'];
        nums[8] = counts['g'];
        nums[1] = counts['o'] - nums[0] - nums[2] - nums[4];
        nums[3] = counts['h'] - nums[8];
        nums[5] = counts['f'] - nums[4];
        nums[7] = counts['s'] - nums[6];
        nums[9] = counts['i'] - nums[6] - nums[8] - nums[5];
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = 0; j < nums[i]; ++j) {
                res += (i + '0');
            }
        }
        return res;
    }
};

參考資料: