-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ff750c6
commit 9f094db
Showing
3 changed files
with
60 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletions
9
src/page-11/1143. Longest Common Subsequence/longestCommonSubsequence.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { longestCommonSubsequence } from './longestCommonSubsequence'; | ||
|
||
describe('1143. Longest Common Subsequence', () => { | ||
test('longestCommonSubsequence', () => { | ||
expect(longestCommonSubsequence('abcde', 'ace')).toBe(3); | ||
expect(longestCommonSubsequence('abc', 'abc')).toBe(3); | ||
expect(longestCommonSubsequence('abc', 'def')).toBe(0); | ||
}); | ||
}); |
26 changes: 26 additions & 0 deletions
26
src/page-11/1143. Longest Common Subsequence/longestCommonSubsequence.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
type LongestCommonSubsequence = (text1: string, text2: string) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const longestCommonSubsequence: LongestCommonSubsequence = (text1, text2) => { | ||
const m = text1.length; | ||
const n = text2.length; | ||
|
||
// Initialize a (m+1) x (n+1) DP array with zeros | ||
const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); | ||
|
||
// Fill in the DP array | ||
for (let i = 1; i <= m; i++) { | ||
for (let j = 1; j <= n; j++) { | ||
if (text1[i - 1] === text2[j - 1]) { | ||
dp[i][j] = dp[i - 1][j - 1] + 1; | ||
} else { | ||
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); | ||
} | ||
} | ||
} | ||
|
||
// The length of the longest common subsequence is found at dp[m][n] | ||
return dp[m][n]; | ||
}; |