Skip to content

Commit dd782fd

Browse files
authored
Merge pull request #331 from soapyigu/DP
Add a solution to the Longest Common Subsequence
2 parents ac68cb1 + d3f143a commit dd782fd

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

DP/LongestCommonSubsequence.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/longest-common-subsequence/
3+
* Primary idea: Dynamic Programming, dp[i][j] = dp[i - 1][j - 1] + 1 or max(dp[i - 1][j], dp[i][j - 1])
4+
*
5+
* Time Complexity: O(mn), Space Complexity: O(1)
6+
*/
7+
8+
class LongestCommonSubsequence {
9+
func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int {
10+
let text1Chars = Array(text1), text2Chars = Array(text2)
11+
let m = text1.count, n = text2.count
12+
var dp = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1)
13+
14+
for i in 1...m {
15+
for j in 1...n {
16+
if text1Chars[i - 1] == text2Chars[j - 1] {
17+
dp[i][j] = dp[i - 1][j - 1] + 1
18+
} else {
19+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
20+
}
21+
}
22+
}
23+
24+
return dp[m][n]
25+
}
26+
}

0 commit comments

Comments
 (0)