LeetCode 423. Reconstruct Original Digits from English

本文介绍了一种从乱序的英文数字表述中提取并按升序排列数字的算法。该算法通过分析特定字符出现的次数来确定每个数字出现的频次,并最终输出排序后的数字串。文章详细解释了算法的具体实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"

class Solution {
public:
    string originalDigits(string s) {
        vector<int> letters(26,0);
        for (auto c: s) {
            ++letters[c - 'a']; 
        }
        vector<string> words = {"zero", "two", "four", "six", "eight", "one", "three", "five", "seven", "nine"};
        vector<int> order = {0, 2, 4, 6, 8, 1, 3, 5, 7, 9};
        vector<char> dis_char = {'z', 'w', 'u', 'x', 'g', 'o', 'r', 'f', 'v', 'i'};
        vector<int> counts(10, 0);
        for (int i = 0;i < 10; ++i) {
            int num = letters[dis_char[i] - 'a'];
            counts[order[i]] = num;
            for (auto c: words[i]) {
                letters[c - 'a'] -= num;
            }
        }
        string result;
        for (int i = 0; i < 10; ++i) {
            result += string(counts[i], char(i +'0'));
        }
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值