LeetCode-1143. Longest Common Subsequence

网友投稿 666 2022-08-25

LeetCode-1143. Longest Common Subsequence

LeetCode-1143. Longest Common Subsequence

Given two strings ​​text1​​​ and ​​text2​​, return the length of their longest common subsequence.

A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

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: 3Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"Output: 0Explanation: There is no such common subsequence, so the result is 0.

Constraints:

​​1 <= text1.length <= 1000​​​​1 <= text2.length <= 1000​​The input strings consist of lowercase English characters only.

题解:

go:

func max(a, b int) int { if a > b { return a } return b}func longestCommonSubsequence(text1 string, text2 string) int { l1, l2 := len(text1), len(text2) dp := make([][]int, l1 + 1) for i := 0; i <= l1; i++ { dp[i] = make([]int, l2 + 1) } for i := 0; i < l1; i++ { for j := 0; j < l2; j++ { if text1[i] == text2[j] { dp[i + 1][j + 1] = dp[i][j] + 1 } else { dp[i + 1][j + 1] = max(max(dp[i + 1][j], dp[i][j + 1]), dp[i][j]) } } } return dp[l1][l2]}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:JSP开发过程遇到的中文乱码问题及解决方案(jsp代码乱码)
下一篇:华为-称砝码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~