下面是分别解决最长上升子序列、最大连续子序列和和最长公共子串问题的Java代码示例:
最长上升子序列(Longest Increasing Subsequence):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class LongestIncreasingSubsequence {
public static int lengthOfLIS(int[] nums) { int n = nums.length; int[] dp = new int[n]; int maxLen = 0;
for (int i = 0; i < n; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[i] > nums[j]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } maxLen = Math.max(maxLen, dp[i]); }
return maxLen; }
public static void main(String[] args) { int[] nums = {10, 9, 2, 5, 3, 7, 101, 18}; int lisLength = lengthOfLIS(nums); System.out.println("Length of Longest Increasing Subsequence: " + lisLength); } }
|
最大连续子序列和(Maximum Subarray Sum):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class MaximumSubarraySum {
public static int maxSubArraySum(int[] nums) { int n = nums.length; int maxSum = nums[0]; int currentSum = nums[0];
for (int i = 1; i < n; i++) { currentSum = Math.max(nums[i], currentSum + nums[i]); maxSum = Math.max(maxSum, currentSum); }
return maxSum; }
public static void main(String[] args) { int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; int maxSum = maxSubArraySum(nums); System.out.println("Maximum Subarray Sum: " + maxSum); } }
|
最长公共子串(Longest Common Substring):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class LongestCommonSubstring {
public static int longestCommonSubstring(String s1, String s2) { int m = s1.length(); int n = s2.length(); int[][] dp = new int[m + 1][n + 1]; int maxLength = 0;
for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s1.charAt(i - 1) == s2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; maxLength = Math.max(maxLength, dp[i][j]); } } }
return maxLength; }
public static void main(String[] args) { String s1 = "ABABC"; String s2 = "BABCBA"; int commonSubstringLength = longestCommonSubstring(s1, s2); System.out.println("Length of Longest Common Substring: " + commonSubstringLength); } }
|
这些示例分别展示了如何解决最长上升子序列、最大连续子序列和和最长公共子串问题。实际应用中,根据问题的需求可能需要进行适当的修改。