题目
给你一个字符串 s
,其中包含字母顺序打乱的用英文单词表示的若干数字(0-9
)。按 升序 返回原始的数字。
示例 1:
1 2
| 输入:s = "owoztneoer" 输出:"012"
|
示例 2:
1 2
| 输入:s = "fviefuro" 输出:"45"
|
提示:
- 1 <= s.length <= 105
- s[i] 为 [“e”,”g”,”f”,”i”,”h”,”o”,”n”,”s”,”r”,”u”,”t”,”w”,”v”,”x”,”z”] 这些字符之一
- s 保证是一个符合题目要求的字符串
解答
看完题目后,大概猜出可能需要每个数字的特定字母做标识,所以干脆列出0-9数字的英文单词观察
1 2 3 4 5 6 7 8 9 10
| public static final String ZERO = "zero"; public static final String ONE = "one"; public static final String TWO = "two"; public static final String THREE = "three"; public static final String FOUR = "four"; public static final String FIVE = "five"; public static final String SIX = "six"; public static final String SEVEN = "seven"; public static final String EIGHT = "eight"; public static final String NINE = "nine";
|
如上,观察后得出,可以分三轮,计算出每个数字的出现次数
得出方法后,代码就很容易写了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import java.util.HashMap; import java.util.Map; import java.util.Optional;
class Solution { public String originalDigits(String s) { Map<Character, Integer> wordCount = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if( wordCount.containsKey(c) ){ wordCount.put(c, wordCount.get(c)+1); } else { wordCount.put(c, 1); } }
int[] numCount = new int[10]; numCount[0] = Optional.ofNullable(wordCount.get('z')).orElse(0); numCount[2] = Optional.ofNullable(wordCount.get('w')).orElse(0); numCount[4] = Optional.ofNullable(wordCount.get('u')).orElse(0); numCount[6] = Optional.ofNullable(wordCount.get('x')).orElse(0); numCount[8] = Optional.ofNullable(wordCount.get('g')).orElse(0); numCount[1] = Optional.ofNullable(wordCount.get('o')).orElse(0)-numCount[0]-numCount[2]-numCount[4]; numCount[3] = Optional.ofNullable(wordCount.get('r')).orElse(0)-numCount[0]-numCount[4]; numCount[5] = Optional.ofNullable(wordCount.get('f')).orElse(0)-numCount[4]; numCount[7] = Optional.ofNullable(wordCount.get('s')).orElse(0)-numCount[6]; numCount[9] = Optional.ofNullable(wordCount.get('i')).orElse(0)-numCount[5]-numCount[6]-numCount[8];
StringBuilder sb = new StringBuilder(); for (int i = 0; i < numCount.length; i++) { for (int j = 0; j < numCount[i]; j++) { sb.append(i); } } return sb.toString(); } }
|
题目转载自:https://leetcode-cn.com/problems/reconstruct-original-digits-from-english