1143. Longest Common Subsequence
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
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.
- For example,
"ace"is a subsequence of"abcde".
A common subsequence of two strings is a subsequence that is common to both strings.
题目解析:
- 最长公共子串和最长公共子序列的区别:
- 子串只考虑当前尾部元素相等时的情况:dp[i][j]表示包含i,j的最长公共子串
- 子序列因为不是连续的,所以尾部元素不一定相等:dp[i][j]表示最长公共子序列,可以不包含i,j
代码:
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int n = text1.length(), m = text2.length();
int[][] dp = new int[n+1][m+1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (text1.charAt(i) == text2.charAt(j)) {
dp[i+1][j+1] = dp[i][j] + 1;
} else {
dp[i+1][j+1] = Math.max(dp[i+1][j], dp[i][j+1]);
}
}
}
return dp[n][m];
}
}
1035. Uncrossed Lines
You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:
nums1[i] == nums2[j], and- the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return the maximum number of connecting lines we can draw in this way.
题目解析:
- 与上题类似
代码:
class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
int[][] dp = new int[nums1.length + 1][nums2.length + 1];
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] == nums2[j]) {
dp[i+1][j+1] = dp[i][j] + 1;
} else {
dp[i+1][j+1] = Math.max(dp[i+1][j], dp[i][j+1]);
}
}
}
return dp[nums1.length][nums2.length];
}
}
53. Maximum Subarray
Given an integer array nums, find the subarray with the largest sum, and return its sum.
题目解析:
- 如果数组和为负数,直接跳过,因为任何数组加上该数组的和都会变小
代码:
class Solution {
public int maxSubArray(int[] nums) {
int max = Integer.MIN_VALUE;
int[] dp = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
if (dp[i] < 0 || dp[i] + nums[i] < 0) {
dp[i+1] = nums[i];
} else {
dp[i+1] = dp[i] + nums[i];
}
max = Math.max(max, dp[i+1]);
}
return max;
}
}