博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 1143. Longest Common Subsequence
阅读量:4621 次
发布时间:2019-06-09

本文共 1735 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

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

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.

题解:

dp[i][j] stands for length of LCS between text1 up to i and text2 up to j.

If text1.charAt(i) == text2.charAt(j), dp[i][j] = dp[i-1][j-1] + 1.

Otherwise, dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]).

如果不放心的话,就直接取上述三个的最小.

Time Complexity: O(m*n). m = text1.length. n = text2.length.

Space: O(m*n).

AC Java: 

1 class Solution { 2     public int longestCommonSubsequence(String text1, String text2) { 3         if(text1 == null || text1.length() == 0 || text2 == null || text2.length() == 0){ 4             return 0; 5         } 6          7         int m = text1.length(); 8         int n = text2.length(); 9         int [][] dp = new int[m+1][n+1];10         for(int i = 0; i

类似, .

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11450819.html

你可能感兴趣的文章
转:android 自定义RadioButton样式
查看>>
HTTP请求过程
查看>>
织梦多域名解析到同一个空间导致打开链接不一致怎么办?
查看>>
Xcode10 library not found for -lstdc++ 找不到问题
查看>>
Mysql 8.0.13如何重置密码
查看>>
发布功能完成
查看>>
excel 合并单元格
查看>>
iOS设计模式简介
查看>>
c# 扩展方法 奇思妙用 高级篇 九:OrderBy(string propertyName, bool desc)
查看>>
C语言中的地址传递(传指针,传递给形参的指针仍然是实参指针的一份拷贝)
查看>>
redis缓存数据库及Python操作redis
查看>>
opencms忘记Admin用户登录密码解决方案
查看>>
forms组件
查看>>
create-react-app 配置sass
查看>>
02_关系数据库
查看>>
在win7电脑中如何查看运行进程的PID标识符
查看>>
[Vue] vue-cli3.0安装
查看>>
C++学习之字符串
查看>>
图像化列表
查看>>
2014年10月9日——语言基础2
查看>>