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.
Example 1:
Input: "owoztneoer" Output: "012"
Example 2:
Input: "fviefuro" Output: "45"
Subscribe to see which companies asked this question
最开始是用暴力算法,挨个数字判断,是不是在里面,结果超时了
那就只能采用奸诈的方法,观察数字的特殊性,比如有z的一定是zero,有x的一定是six,然后挨个排除,发现根据十个字母就都能计算出来了
计算的过程如下所示
class Solution(object):
def originalDigits(self, s):
res = ''
z = s.count('z')
x = s.count('x')
g = s.count('g')
h = s.count('h')
t = s.count('t')
ss = s.count('s')
v = s.count('v')
f = s.count('f')
i = s.count('i')
o = s.count('o')
print z,x,g,h,t,ss,v,f,i,o
res += '0' * z
res += '1' *(o-(f-(v-ss+x))-(t-h)-z)
res += '2' * (t-h)
res += '3' * (h-g)
res += '4' * (f-(v-ss+x))
res += '5' * (v-ss+x)
res += '6' * x
res += '7' * (ss-x)
res += '8' * g
res += '9' * (i-(v-ss+x)-g-x)
#res.sort()
return res
'''
def check(self,s,num):
for i in num:
if i not in s:
return False
return True
tnums = ['zero','one','two','three','four','five','six','seven','eight','nine']
nums = []
for i in tnums:
i = i.decode()
i = list(i)
#print i
nums += i,
#print nums
s = list(s)
#s.remove('o')
#print s
res = ''
while s:
#print s
for i in nums:
if self.check(s,i):
res += str(nums.index(i))
for ii in i:
s.remove(ii)
return res
'''
"""
:type s: str
:rtype: str
"""