You can apply this algorithm:
First count the occurrence of each letter in the input string. For example, the example input string has these occurrences:
{
"e": 4,
"f": 1,
"g": 1,
"h": 1,
"i": 2,
"n": 3,
"o": 1,
"r": 1,
"s": 1,
"t": 1,
"u": 1,
"v": 1,
"w": 0,
"x": 0,
"z": 0
}
I also included unused letters, as they would play a role in "two", "six" and "zero", but they are not represented in this example input.
Now we can observe that:
- Every "z" in the input belongs to a "zero";
- Every "w" belongs to a "two";
- Every "u" belongs to a "four";
- Every "x" belongs to a "six";
- Every "g" belongs to an "eight"
If you find the number of "z" in the input string, you can deduct there are that many occurrences of "zero", and you can deduct that count from "z", "e", "r", and "o". That many "0" should be recorded for the output.
Once we have done that for the above, we can continue with the following:
- Every remaining "o" belongs to a "one" (since all "zero", "two", "four" were already accounted for by this time).
- Every remaining "h" belongs to a "three"
- Every remaining "f" belongs to a "five"
- Every remaining "s" belongs to a "seven"
And after those have been accounted for, we can finally conclude that:
- Every remaining "i" belongs to a "nine"
We can simplify a bit, because some letters don't really play a role in deciding which digits are represented. For instance, in the above logic, we don't care about the number of "n" or "e", so we might as well not reduce their count when we detect a "one", ...etc. The only 10 letters we care about are listed above.
Finally we use the counts for each digit to build the sorted string.
Here is an implementation in JavaScript. It runs the algorithm for the example input. There is no input validation... It is assumed to be a valid combination of digit names:
// reference data. The identifying letter is put at the front,
// and the letters that still matter for another digit
// follow it.
let map = [
["zo", "0"],
["wo", "2"],
["ufo", "4"],
["xis", "6"],
["gih", "8"],
["o", "1"],
["h", "3"],
["fi", "5"],
["s", "7"],
["i", "9"]
];
// The algorithm
function decimals(s) {
// Count occurrences of letters
let charCount = {};
for (let c of "efghinorstuvwxz") charCount[c] = 0;
for (let c of s) charCount[c]++;
// Recognise digits by their identifying letter
let digitCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (let [name, digit] of map) {
let frequency = charCount[name[0]];
for (let letter of name) charCount[letter] -= frequency;
digitCount[digit] = frequency;
}
// Build the result string
let result = "";
for (let digit of "9876543210") result += digit.repeat(digitCount[digit]);
return result;
}
// Example run
let result = decimals("nieignhtesevfouenr");
console.log(result);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…