Skip to content

Commit 9e2c366

Browse files
committedFeb 14, 2025
Add solution #1143
1 parent 8826f2a commit 9e2c366

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,7 @@
397397
1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy|
398398
1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy|
399399
1137|[N-th Tribonacci Number](./1137-n-th-tribonacci-number.js)|Easy|
400+
1143|[Longest Common Subsequence](./1143-longest-common-subsequence.js)|Medium|
400401
1161|[Maximum Level Sum of a Binary Tree](./1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
401402
1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy|
402403
1200|[Minimum Absolute Difference](./1200-minimum-absolute-difference.js)|Easy|
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 1143. Longest Common Subsequence
3+
* https://leetcode.com/problems/longest-common-subsequence/
4+
* Difficulty: Medium
5+
*
6+
* Given two strings text1 and text2, return the length of their longest common subsequence.
7+
* If there is no common subsequence, return 0.
8+
*
9+
* A subsequence of a string is a new string generated from the original string with some
10+
* characters (can be none) deleted without changing the relative order of the remaining
11+
* characters.
12+
*
13+
* - For example, "ace" is a subsequence of "abcde".
14+
*
15+
* A common subsequence of two strings is a subsequence that is common to both strings.
16+
*/
17+
18+
/**
19+
* @param {string} text1
20+
* @param {string} text2
21+
* @return {number}
22+
*/
23+
var longestCommonSubsequence = function(text1, text2) {
24+
const dp = new Array(text1.length + 1).fill(0).map(() => new Array(text2.length + 1).fill(0));
25+
26+
for (let i = 1; i <= text1.length; i++) {
27+
for (let j = 1; j <= text2.length; j++) {
28+
if (text1.charAt(i - 1) === text2.charAt(j - 1)) {
29+
dp[i][j] = dp[i - 1][j - 1] + 1;
30+
} else {
31+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
32+
}
33+
}
34+
}
35+
36+
return dp[text1.length][text2.length];
37+
};

0 commit comments

Comments
 (0)
Please sign in to comment.