#1143

Longest Common Subsequence

specialist · 725 · lc medium +31 · verified · 58.9% accepted · 14,993 likes · top 56%

Description

You are given two strings text1 and text2. Find and return the length of the longest subsequence shared by both strings. If the two strings share no common subsequence, return 0.

A subsequence is derived from a string by removing zero or more characters while keeping the remaining characters in their original relative order. For instance, "ace" is a valid subsequence of "abcde".

A common subsequence is any subsequence that appears in both text1 and text2.

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.

Code

1
2
3