Skip to content

Commit 2b1997a

Browse files
committed
Swift Implementation for LCCI 17.13
1 parent a88a827 commit 2b1997a

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

lcci/17.13.Re-Space/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,28 @@ func respace(dictionary []string, sentence string) int {
108108
}
109109
```
110110

111+
```swift
112+
class Solution {
113+
func respace(_ dictionary: [String], _ sentence: String) -> Int {
114+
let dict = Set(dictionary)
115+
let n = sentence.count
116+
var dp = [Int](repeating: 0, count: n + 1)
117+
let sentenceArray = Array(sentence)
118+
119+
for i in 1...n {
120+
dp[i] = dp[i - 1] + 1
121+
for j in 0..<i {
122+
let sub = String(sentenceArray[j..<i])
123+
if dict.contains(sub) {
124+
dp[i] = min(dp[i], dp[j])
125+
}
126+
}
127+
}
128+
return dp[n]
129+
}
130+
}
131+
```
132+
111133
<!-- tabs:end -->
112134

113135
<!-- end -->

lcci/17.13.Re-Space/README_EN.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,28 @@ func respace(dictionary []string, sentence string) int {
113113
}
114114
```
115115

116+
```swift
117+
class Solution {
118+
func respace(_ dictionary: [String], _ sentence: String) -> Int {
119+
let dict = Set(dictionary)
120+
let n = sentence.count
121+
var dp = [Int](repeating: 0, count: n + 1)
122+
let sentenceArray = Array(sentence)
123+
124+
for i in 1...n {
125+
dp[i] = dp[i - 1] + 1
126+
for j in 0..<i {
127+
let sub = String(sentenceArray[j..<i])
128+
if dict.contains(sub) {
129+
dp[i] = min(dp[i], dp[j])
130+
}
131+
}
132+
}
133+
return dp[n]
134+
}
135+
}
136+
```
137+
116138
<!-- tabs:end -->
117139

118140
<!-- end -->

lcci/17.13.Re-Space/Solution.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
func respace(_ dictionary: [String], _ sentence: String) -> Int {
3+
let dict = Set(dictionary)
4+
let n = sentence.count
5+
var dp = [Int](repeating: 0, count: n + 1)
6+
let sentenceArray = Array(sentence)
7+
8+
for i in 1...n {
9+
dp[i] = dp[i - 1] + 1
10+
for j in 0..<i {
11+
let sub = String(sentenceArray[j..<i])
12+
if dict.contains(sub) {
13+
dp[i] = min(dp[i], dp[j])
14+
}
15+
}
16+
}
17+
return dp[n]
18+
}
19+
}

0 commit comments

Comments
 (0)