150强访谈中等

最长公共子序列

“最长公共子序列”问题的详细指南和 Python 实现。

问题陈述

中等

给定两个字符串 text1 和 text2,返回它们的最长公共子序列的长度。如果没有公共子序列,则返回0。

字符串的子序列是在原字符串中删除一些字符(可以没有)而生成的新字符串,而不改变其余字符的相对顺序。 (例如,“ace”是“abcde”的子序列)。

编写一个函数 longestCommonSubsequence(text1: str, text2: str) -> int

约束条件
  • 1 <= len(text1), len(text2) <= 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 common subsequence, so the result is 0.

Need a Hint?
考虑使用 2D DP 特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。