Reconstruct Original Digits from English 问题及解法

来源:互联网 发布:c语言栈实现四则运算 编辑:程序博客网 时间:2024/06/08 10:53

问题描述:

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.

示例:

Input: "owoztneoer"Output: "012"
Input: "fviefuro"Output: "45"

问题分析:

根据每个数字中特有的代表字母,先把0,2,4,6,8的个数求出来,之后跟根据剩余的字母求出1,3,5,7,9的个数。


过程详见代码:

class Solution {public:    string originalDigits(string s) {        vector<int> m(26, 0);vector<int> res(10, 0);vector<pair<string, int>> digits = { pair<string, int>("zero", 0), pair<string, int>("two", 2), pair<string, int>("four", 4), pair<string, int>("six", 6), pair<string, int>("eight", 8), pair<string, int>("one", 1), pair<string, int>("three", 3),pair<string, int>("five", 5), pair<string, int>("seven", 7), pair<string, int>("nine", 9) };vector<int> flag = { 'z', 'w', 'u', 'x', 'g', 'o', 'r', 'f', 's', 'i' };for (char c : s){m[c - 'a']++;}// 首先我们先找出0,2,4,6,8数字的个数,然后是1,3,5,7,9for (int i = 0; i < digits.size(); i++){string num = digits[i].first;int digit = digits[i].second;res[digit] = m[flag[i] - 'a'];for (char c : num){m[c - 'a'] -= res[digit];}}string sr = "";for (int i = 0; i < 10; i++){if (res[i])sr.append(res[i],char(i + '0'));}return sr;    }};