java最长子序列算法,JAVA算法:最长重复子序列(JAVA)

本文探讨了两种不同的Java算法来解决最长重复子序列问题:一是使用动态规划,通过二维数组求解字符串中不考虑相同位置字符的最长重复子序列长度;二是递归方法,强调字符匹配条件下的子序列长度计算。两种方法均给出了详细示例和运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA算法:最长重复子序列(JAVA)

Longest Repeating Subsequence

Given a string, find length of the longest repeating subseequence such that the two subsequence don’t have same string character at same position, i.e., any i’th character in the two subsequences shouldn’t have the same index in the original string.

8da45e9bc3042d0e1dd1518c9bec449b.png

算法设计

package com.bean.algorithm.basic;

public class LongestRepeatingSubsequence {

// Function to find the longest repeating subsequence

static int findLongestRepeatingSubSeq(String str) {

int n = str.length();

// Create and initialize DP table

int[][] dp = new int[n + 1][n + 1];

// Fill dp table (similar to LCS loops)

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

// If characters match and indexes are not same

if (str.charAt(i - 1) == str.charAt(j - 1) && i != j)

dp[i][j] = 1 + dp[i - 1][j - 1];

// If characters do not match

else

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

}

}

return dp[n][n];

}

// driver program to check above function

public static void main(String[] args) {

String str = "aabb";

System.out.println("The length of the largest subsequence that" + " repeats itself is : "

+ findLongestRepeatingSubSeq(str));

}

}

程序运行结果:

The length of the largest subsequence that repeats itself is : 2

另外一种算法设计——递归算法 Recursion

package com.bean.algorithm.basic;

import java.util.Arrays;

public class LongestRepeatingSubsequence2 {

static int dp[][] = new int[1000][1000];

// This function mainly returns LCS(str, str)

// with a condition that same characters at

// same index are not considered.

static int findLongestRepeatingSubSeq(char X[], int m, int n) {

if (dp[m][n] != -1) {

return dp[m][n];

}

// return if we have reached the end of either string

if (m == 0 || n == 0) {

return dp[m][n] = 0;

}

// if characters at index m and n matches

// and index is different

if (X[m - 1] == X[n - 1] && m != n) {

return dp[m][n] = findLongestRepeatingSubSeq(X, m - 1, n - 1) + 1;

}

// else if characters at index m and n don't match

return dp[m][n] = Math.max(findLongestRepeatingSubSeq(X, m, n - 1), findLongestRepeatingSubSeq(X, m - 1, n));

}

// Longest Repeated Subsequence Problem

static public void main(String[] args) {

String str = "aabb";

int m = str.length();

for (int[] row : dp) {

Arrays.fill(row, -1);

}

System.out.println("The length of the largest subsequence that" + " repeats itself is : "

+ findLongestRepeatingSubSeq(str.toCharArray(), m, m));

}

}

程序运行结果:

The length of the largest subsequence that repeats itself is : 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值