diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" index eafbc0baaa62c..ed70055c0ae18 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" @@ -275,6 +275,30 @@ class Solution { } ``` +#### Swift + +```swift +class Solution { + func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int { + let m = text1.count, n = text2.count + let text1Array = Array(text1) + let text2Array = Array(text2) + var f = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1) + + for i in 1...m { + for j in 1...n { + if text1Array[i - 1] == text2Array[j - 1] { + f[i][j] = f[i - 1][j - 1] + 1 + } else { + f[i][j] = max(f[i - 1][j], f[i][j - 1]) + } + } + } + return f[m][n] + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.swift" new file mode 100644 index 0000000000000..33b58c9c221ab --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/Solution.swift" @@ -0,0 +1,19 @@ +class Solution { + func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int { + let m = text1.count, n = text2.count + let text1Array = Array(text1) + let text2Array = Array(text2) + var f = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1) + + for i in 1...m { + for j in 1...n { + if text1Array[i - 1] == text2Array[j - 1] { + f[i][j] = f[i - 1][j - 1] + 1 + } else { + f[i][j] = max(f[i - 1][j], f[i][j - 1]) + } + } + } + return f[m][n] + } +} \ No newline at end of file