diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" index f1a510583f5fb..16f027f2b14a5 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" @@ -281,6 +281,44 @@ public class Solution { } ``` +#### Swift + +```swift +class Solution { + private var memo: [[Bool?]] = [] + private var s: [Character] = [] + private var p: [Character] = [] + private var m: Int = 0 + private var n: Int = 0 + + func isMatch(_ s: String, _ p: String) -> Bool { + self.s = Array(s) + self.p = Array(p) + self.m = s.count + self.n = p.count + self.memo = Array(repeating: Array(repeating: nil, count: n + 1), count: m + 1) + return dfs(0, 0) + } + + private func dfs(_ i: Int, _ j: Int) -> Bool { + if j >= n { + return i == m + } + if let res = memo[i][j] { + return res + } + var res = false + if j + 1 < n && p[j + 1] == "*" { + res = dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j)) + } else { + res = i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j + 1) + } + memo[i][j] = res + return res + } +} +``` + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.swift" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.swift" new file mode 100644 index 0000000000000..a2c2093d659af --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/Solution.swift" @@ -0,0 +1,33 @@ +class Solution { + private var memo: [[Bool?]] = [] + private var s: [Character] = [] + private var p: [Character] = [] + private var m: Int = 0 + private var n: Int = 0 + + func isMatch(_ s: String, _ p: String) -> Bool { + self.s = Array(s) + self.p = Array(p) + self.m = s.count + self.n = p.count + self.memo = Array(repeating: Array(repeating: nil, count: n + 1), count: m + 1) + return dfs(0, 0) + } + + private func dfs(_ i: Int, _ j: Int) -> Bool { + if j >= n { + return i == m + } + if let res = memo[i][j] { + return res + } + var res = false + if j + 1 < n && p[j + 1] == "*" { + res = dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j)) + } else { + res = i < m && (s[i] == p[j] || p[j] == ".") && dfs(i + 1, j + 1) + } + memo[i][j] = res + return res + } +} \ No newline at end of file