Reconstruct Original Digits from Englishgit
Given a non-empty string containing an out-of-order English representation of digits 0-9
, output the digits in ascending order.less
Note:this
Example 1:spa
Input: "owoztneoer" Output: "012"
Example 2:code
Input: "fviefuro" Output: "45"
Subscribe to see which companies asked this question.orm
快兩年沒更新博客了,今天看了一下Leetcode,都500多道題了,就隨便交了一道。blog
開始考慮到用DFS,可是考慮到有些Digit能夠由一個字母惟一確認,而後推算了一下,發現全部Digit均可以肯定,就直接算答案了。很久沒刷過題了,代碼質量直線降低啊。three
class Solution { public: void update(int* count, string s, int n) { for (auto c : s) { count[c - 'a'] -= n; } }
string originalDigits(string s) { vector<string> dict = {"zero", "one", "two", "three", "fore", "five", "six", "seven", "eight", "nine"}; int digitOrder[10] = {0, 8, 6, 2, 3, 7, 5, 4, 1, 9}; char keyOrder[10] = {'z', 'g', 'x', 'w', 'h', 's', 'v', 'f', 'o', 'i'}; int count[26] = {0}; for (auto c : s) { ++count[c - 'a']; } int res[10] = {0}; for (int i = 0; i < 10; ++i) { res[digitOrder[i]] = count[keyOrder[i] - 'a']; update(count, dict[digitOrder[i]], res[digitOrder[i]]); } string str = ""; for (int i = 0; i < 10; ++i) { for (int j = 0; j < res[i]; ++j) { str += ('0' + i); } } return str; } };