-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path423_ReconstructOriginalDigitsFromEnglish.swift
96 lines (88 loc) · 2.94 KB
/
423_ReconstructOriginalDigitsFromEnglish.swift
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Solution {
func originalDigits(_ s: String) -> String {
let letters:[Character:Int] = [
"z":0,
"x":6,
"w":2,
"u":4,
"g":8,
"t":3,
"f":5,
"s":7,
"o":1,
"n":9]
var map = [Character: Int]()
var result = [Int]()
for c in s {
map[c] = (map[c] ?? 0) + 1
}
for letter in "zxwugtfso" {
if let count = map[letter] {
reduceWords(letter, count, &map)
result += Array(repeating:letters[letter]!, count:count)
}
}
if let count = map["e"] {
result.append(contentsOf: Array(repeating:9, count:count))
}
var returnValue = ""
for i in result.sorted() {
returnValue += "\(i)"
}
return returnValue
}
func reduceWords(_ letter: Character, _ n:Int, _ map: inout [Character:Int]) {
switch letter {
case "z"://zero
reduceLetters("z", n, &map)
reduceLetters("e", n, &map)
reduceLetters("r", n, &map)
reduceLetters("o", n, &map)
case "x"://six
reduceLetters("s", n, &map)
reduceLetters("i", n, &map)
reduceLetters("x", n, &map)
case "w":
reduceLetters("t", n, &map)
reduceLetters("w", n, &map)
reduceLetters("o", n, &map)
case "u":
reduceLetters("f", n, &map)
reduceLetters("o", n, &map)
reduceLetters("u", n, &map)
reduceLetters("r", n, &map)
case "g":
reduceLetters("e", n, &map)
reduceLetters("i", n, &map)
reduceLetters("g", n, &map)
reduceLetters("h", n, &map)
reduceLetters("t", n, &map)
case "t":
reduceLetters("t", n, &map)
reduceLetters("h", n, &map)
reduceLetters("r", n, &map)
reduceLetters("e", n*2, &map)
case "f":
reduceLetters("f", n, &map)
reduceLetters("i", n, &map)
reduceLetters("v", n, &map)
reduceLetters("e", n, &map)
case "s":
reduceLetters("s", n, &map)
reduceLetters("e", n*2, &map)
reduceLetters("v", n, &map)
reduceLetters("n", n, &map)
case "o":
reduceLetters("o", n, &map)
reduceLetters("n", n, &map)
reduceLetters("e", n, &map)
default:
return
}
}
func reduceLetters(_ letter: Character, _ n:Int, _ map: inout [Character: Int]) {
if let count = map[letter] {
map[letter] = count-n
}
}
}