Skip to content

Commit 2ea0a3e

Browse files
committed
feat: Add solution for LeetCode problem 139
1 parent 166f370 commit 2ea0a3e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

word-break/WhiteHyun.swift

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//
2+
// 139. Word Break
3+
// https://leetcode.com/problems/word-break/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/07/14.
7+
//
8+
9+
class Solution {
10+
func wordBreak(_ s: String, _ wordDict: [String]) -> Bool {
11+
var cache: [String: Bool] = [:]
12+
13+
func helper(_ string: String) -> Bool {
14+
if let result = cache[string] {
15+
return result
16+
}
17+
18+
if string.isEmpty {
19+
cache[string] = true
20+
return true
21+
}
22+
23+
for word in wordDict where string.hasPrefix(word) {
24+
if helper(String(string.dropFirst(word.count))) {
25+
cache[string] = true
26+
return true
27+
}
28+
}
29+
30+
cache[string] = false
31+
return false
32+
}
33+
34+
return helper(s)
35+
}
36+
}

0 commit comments

Comments
 (0)