题目地址
https://leetcode.com/problems/reconstruct-original-digits-from-english/
题目描述
423. Reconstruct Original Digits from English
Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.
Example 1:
Input: s = "owoztneoer"
Output: "012"
Example 2:
Input: s = "fviefuro"
Output: "45"
思路
- hashmap统计出每一个字符的count.
- 对应的数字实际上是脑筋急转弯.
- z对应0, w对应2, u对应4, x对应6, g对应8. 单次且仅在这几个数出现, 因此偶数全部可以确定.
- 之后推理出单数.
- 3对应h的数量减去8的数量. 5对应f的数量减去4的数量, 7对应s的数量减去6的数量. 9对应i的数量减去5, 6, 8的数量. 1对应n的数量减去7, 和9的两倍数量.
关键点
代码
- 语言支持:Java
class Solution {
public String originalDigits(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c: s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
int[] res = new int[10];
res[0] = map.getOrDefault('z', 0);
res[2] = map.getOrDefault('w', 0);
res[4] = map.getOrDefault('u', 0);
res[6] = map.getOrDefault('x', 0);
res[8] = map.getOrDefault('g', 0);
res[3] = map.getOrDefault('h', 0) - res[8];
res[5] = map.getOrDefault('f', 0) - res[4];
res[7] = map.getOrDefault('s', 0) - res[6];
res[9] = map.getOrDefault('i', 0) - res[5] - res[6] - res[8];
res[1] = map.getOrDefault('n', 0) - res[7] - 2 * res[9];
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < res[i]; j++) {
sb.append(i);
}
}
return sb.toString();
}
}
网友评论