您的位置:首页 > 其它

LeetCode: Reconstruct Original Digits from English

2016-10-16 16:49 555 查看
这道 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: