LeetCode: Reconstruct Original Digits from English

这道 LeetCode 上的题目,还是有点难度,有点意思的。就是要把给定的字符串中的英文,组合成 0,1,2,3,4,5,6,7,8,9 这几个数字的英文,再按升序将数字输出。

具体的,题目描述如下:

Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.

Note:
Input contains only lowercase English letters.

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.

Input length is less than 50,000.

这里写图片描述

参考 discuss 部分,python 实现如下:

import collections

def originalDigits(self, s):
        """
        :type s: str
        :rtype: str
        """
        dic = collections.Counter(s)
        cnt = [0] * 10

        cnt[0] = dic['z']
        for d in 'zero': dic[d] = dic[d] - cnt[0]

        cnt[2] = dic['w']
        for d in 'two': dic[d] = dic[d] - cnt[2]

        cnt[4] = dic['u']
        for d in 'four': dic[d] = dic[d] - cnt[4]

        cnt[6] = dic['x']
        for d in 'six': dic[d] = dic[d] - cnt[6]

        cnt[8] = dic['g']
        for d in 'eight': dic[d] = dic[d] - cnt[8]

        cnt[1] = dic['o']
        for d in 'one': dic[d] = dic[d] - cnt[1]

        cnt[3] = dic['r']
        for d in 'three': dic[d] = dic[d] - cnt[3]

        cnt[5] = dic['f']
        for d in 'five': dic[d] = dic[d] - cnt[5]

        cnt[7] = dic['v']
        for d in 'seven': dic[d] = dic[d] - cnt[7]

        cnt[9] = dic['i']
        for d in 'nine': dic[d] = dic[d] - cnt[9]

        output_s = ''
        for i, c in enumerate(cnt):
            output_s = output_s + str(i) * c

        return output_s

提交结果如下:

这里写图片描述

参考链接:
1. https://discuss.leetcode.com/topic/63389/straightforward-python-solution-o-n
2. https://discuss.leetcode.com/topic/63396/naive-python-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值