题目
给定一个非空字符串,其中包含字母顺序打乱的英文单词表示的数字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();
}
}