力扣 423. 从英文中重建数字

题目

给定一个非空字符串,其中包含字母顺序打乱的英文单词表示的数字0-9。按升序输出原始的数字。

注意:

输入只包含小写英文字母。
输入保证合法并可以转换为原始的数字,这意味着像 “abc” 或 “zerone” 的输入是不允许的。
输入字符串的长度小于 50,000。

示例

输入: “owoztneoer”
输出: “012” (zeroonetwo)

输入: “fviefuro”
输出: “45” (fourfive)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reconstruct-original-digits-from-english
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法1:模拟
Python实现
class Solution:
    def originalDigits(self, s: str) -> str:
        res=list()
        c1=collections.Counter(s)
        v={"6":"six","4":"four","2":"two","8":"eight","7":"seven","5":"five","3":"three","9":"nine","0":"zero","1":"one"}
        c2=dict(v)
        for i,v in c2.items():
            while True:
                if (collections.Counter(v) & c1) == collections.Counter(v):
                    c1 = c1 - collections.Counter(v)
                    res.append(i)
                else:
                    break
        res.sort()
        return "".join(res)

在这里插入图片描述

Java实现
class Solution {
    public String originalDigits(String s) {
        // 记录每个字符的次数
        int[] count = new int[26];
        for (Character ch : s.toCharArray()) {
            count[ch - 'a']++;
        }
        // 记录每个数字单词关键字的次数
        int[] countKey = new int[10];
        countKey[0] = count['z' - 'a'];
        countKey[2] = count['w' - 'a'];
        countKey[4] = count['u' - 'a'];
        countKey[6] = count['x' - 'a'];
        countKey[8] = count['g' - 'a'];
        countKey[3] = count['h' - 'a'] - countKey[8];
        countKey[5] = count['f' - 'a'] - countKey[4];
        countKey[7] = count['v' - 'a'] - countKey[5];
        countKey[1] = count['o' - 'a'] - countKey[0] - countKey[2] - countKey[4];
        countKey[9] = count['i' - 'a'] - countKey[5] - countKey[6] - countKey[8];
        // 存数字次数
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < countKey.length; i++) {
            for (int j = 0; j < countKey[i]; j++) {
                sb.append(i);
            }
        }
        
        return sb.toString();
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值