LeetCode 1143. Longest Common Subsequence

原题链接在这里:https://leetcode.com/problems/longest-common-subsequence/

题目:

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: 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.

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<m; i++){
11             for(int j = 0; j<n; j++){
12                 dp[i+1][j+1] = Math.max(dp[i][j+1], dp[i+1][j]);
13                 if(text1.charAt(i) == text2.charAt(j)){
14                     dp[i+1][j+1] = Math.max(dp[i+1][j+1], dp[i][j]+1);
15                 }                
16             }
17         }
18         
19         return dp[m][n];
20     }
21 }

类似Longest Palindromic.

猜你喜欢

转载自www.cnblogs.com/Dylan-Java-NYC/p/11450819.html