Skip to content

Commit 69ef079

Browse files
committed
feat: add solution to lc problem: No.1143
No.1143.Longest Common Subsequence
1 parent 2370bab commit 69ef079

File tree

3 files changed

+71
-1
lines changed

3 files changed

+71
-1
lines changed

solution/1100-1199/1143.Longest Common Subsequence/README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555

5656
<!-- 这里可写通用的实现逻辑 -->
5757

58-
动态规划法。
58+
**方法一:动态规划**
5959

6060
定义 `dp[i][j]` 表示 `text1[0:i-1]``text2[0:j-1]` 的最长公共子序列(闭区间)。
6161

@@ -156,6 +156,31 @@ func max(a, b int) int {
156156
}
157157
```
158158

159+
### **JavaScript**
160+
161+
```js
162+
/**
163+
* @param {string} text1
164+
* @param {string} text2
165+
* @return {number}
166+
*/
167+
var longestCommonSubsequence = function (text1, text2) {
168+
const m = text1.length;
169+
const n = text2.length;
170+
const dp = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0));
171+
for (let i = 1; i <= m; ++i) {
172+
for (let j = 1; j <= n; ++j) {
173+
if (text1[i - 1] == text2[j - 1]) {
174+
dp[i][j] = dp[i - 1][j - 1] + 1;
175+
} else {
176+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
177+
}
178+
}
179+
}
180+
return dp[m][n];
181+
};
182+
```
183+
159184
### **...**
160185

161186
```

solution/1100-1199/1143.Longest Common Subsequence/README_EN.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,31 @@ func max(a, b int) int {
142142
}
143143
```
144144

145+
### **JavaScript**
146+
147+
```js
148+
/**
149+
* @param {string} text1
150+
* @param {string} text2
151+
* @return {number}
152+
*/
153+
var longestCommonSubsequence = function (text1, text2) {
154+
const m = text1.length;
155+
const n = text2.length;
156+
const dp = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0));
157+
for (let i = 1; i <= m; ++i) {
158+
for (let j = 1; j <= n; ++j) {
159+
if (text1[i - 1] == text2[j - 1]) {
160+
dp[i][j] = dp[i - 1][j - 1] + 1;
161+
} else {
162+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
163+
}
164+
}
165+
}
166+
return dp[m][n];
167+
};
168+
```
169+
145170
### **...**
146171

147172
```
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {string} text1
3+
* @param {string} text2
4+
* @return {number}
5+
*/
6+
var longestCommonSubsequence = function (text1, text2) {
7+
const m = text1.length;
8+
const n = text2.length;
9+
const dp = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0));
10+
for (let i = 1; i <= m; ++i) {
11+
for (let j = 1; j <= n; ++j) {
12+
if (text1[i - 1] == text2[j - 1]) {
13+
dp[i][j] = dp[i - 1][j - 1] + 1;
14+
} else {
15+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
16+
}
17+
}
18+
}
19+
return dp[m][n];
20+
};

0 commit comments

Comments
 (0)