Skip to content

Commit f9a0077

Browse files
committed
[DFS] Update Expression Add Operators with Swift 4
1 parent 0757987 commit f9a0077

File tree

1 file changed

+36
-17
lines changed

1 file changed

+36
-17
lines changed

DFS/ExpressionAddOperators.swift

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,37 +14,56 @@
1414
class ExpressionAddOperators {
1515
func addOperators(_ num: String, _ target: Int) -> [String] {
1616
var res = [String]()
17-
let numChars = Array(num.characters)
18-
19-
guard numChars.count > 0 else {
17+
18+
guard num.count > 0 else {
2019
return res
2120
}
22-
23-
dfs(&res, "", numChars, target, 0, 0, 0)
24-
21+
22+
dfs(&res, "", num, target, 0, 0, 0)
23+
2524
return res
2625
}
27-
28-
private func dfs(_ res: inout [String], _ temp: String, _ numChars: [Character], _ target: Int, _ pos: Int, _ eval: Int, _ mul: Int) {
29-
if pos == numChars.count {
26+
27+
private func dfs(_ res: inout [String], _ temp: String, _ num: String, _ target: Int, _ pos: Int, _ eval: Int, _ mul: Int) {
28+
if pos == num.count {
3029
if eval == target {
3130
res.append(temp)
3231
}
3332
return
3433
}
35-
36-
for i in pos..<numChars.count {
37-
if i != pos && numChars[pos] == "0" {
34+
35+
for i in pos..<num.count {
36+
if i != pos && num[i] == "0" {
3837
break
3938
}
40-
let curt = Int(String(numChars[pos..<i + 1]))!
39+
let curt = Int(num[pos..<i + 1])!
4140
if pos == 0 {
42-
dfs(&res, temp + String(curt), numChars, target, i + 1, curt, curt)
41+
dfs(&res, temp + String(curt), num, target, i + 1, curt, curt)
4342
} else {
44-
dfs(&res, temp + "+" + String(curt), numChars, target, i + 1, eval + curt, curt)
45-
dfs(&res, temp + "-" + String(curt), numChars, target, i + 1, eval - curt, -curt)
46-
dfs(&res, temp + "*" + String(curt), numChars, target, i + 1, eval - mul + mul * curt, mul * curt)
43+
dfs(&res, temp + "+" + String(curt), num, target, i + 1, eval + curt, curt)
44+
dfs(&res, temp + "-" + String(curt), num, target, i + 1, eval - curt, -curt)
45+
dfs(&res, temp + "*" + String(curt), num, target, i + 1, eval - mul + mul * curt, mul * curt)
4746
}
4847
}
4948
}
49+
}
50+
51+
extension String {
52+
subscript(index: Int) -> String {
53+
get {
54+
assert(index < self.count)
55+
return String(Array(self.characters)[index])
56+
}
57+
}
58+
59+
subscript(range: CountableRange<Int>) -> String {
60+
get {
61+
var result = ""
62+
for i in range {
63+
assert(i < self.count)
64+
result.append(self[i])
65+
}
66+
return result
67+
}
68+
}
5069
}

0 commit comments

Comments
 (0)