[JS] Longest Common Subsequence
2022. 9. 13. 14:50
🔒 문제 (LeetCode 1143)
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
- For example, "ace" is a subsequence of "abcde".
A common subsequence of two strings is a subsequence that is common to both strings.
Constraints:
- 1 <= text1.length, text2.length <= 1000
- text1 and text2 consist of only lowercase English characters.
🌊 입출력
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
🔑 해결
🌌 알고리즘 - DP
/**
* @param {string} text1
* @param {string} text2
* @return {number}
*/
var longestCommonSubsequence = function(text1, text2) {
let m = text1.length
let n = text2.length
// dp[i][j] = text1[:i]와 text[:j]의 longest common subsequence
let dp = new Array(m+1).fill().map(() => new Array(n+1).fill(0))
for(let i = 1; i <= m; i++) {
for(let j = 1; j <= n; j++) {
if(text1[i-1] !== text2[j-1]) {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1])
} else {
dp[i][j] = dp[i-1][j-1] + 1
}
}
}
return dp[m][n]
};
'코딩테스트 (JS) > DP' 카테고리의 다른 글
[JS] Edit Distance (0) | 2022.09.17 |
---|---|
[JS] Delete Operation for Two Strings (0) | 2022.09.14 |
[JS] Number of Longest Increasing Subsequence (0) | 2022.09.08 |
[JS] Word Break (0) | 2022.09.07 |
[JS] Decode Ways (0) | 2022.09.07 |