Practice · Dynamic programming (2D) · 2 of 4

Longest Common Subsequence

A subsequence of a string keeps some of its characters, in their original order, and drops the rest: ace is a subsequence of abcde, but aec is not.

Given two strings text1 and text2, return the length of the longest string that is a subsequence of both. If they share no character, return 0.

Example 1

Input
text1 = "stone", text2 = "longest"
Output
3
one appears, in order, in both.

Example 2

Input
text1 = "abc", text2 = "def"
Output
0
The strings share no character.

Constraints

  • text1 and text2 each hold 1 to 1000 lowercase letters.