最长回文子序列 java递归实现

1.如果str的最后一个元素和第一个元素是相同的,则有:lps(0,n-1)=lps(1,n-2)+2;例如字符串序列“AABACACBA”,第一个元素和最后一个元素相同,其中lps(1,n-2)表示红色部分的最长回文子序列的长度;

2.如果str的最后一个元素和第一个元素是不相同的,则有:lps(0,n-1)=max(lps(1,n-1),lps(0,n-2));例如字符串序列“ABACACB”,其中lps(1,n-1)表示去掉第一元素的子序列,lps(0,n-2)表示去掉最后一个元素的子序列。

返回最长回文子序列的长度:

package ddd.lps;

public class LPS {
	public static void main(String args[]) {
		String string = "ACGTGTCAAAATCG";
		System.out.println("最长回文子序列長度为:" + lps(string, 0, string.length() - 1));
	}

	public static int lps(String str, int start, int end) {
		if (start == end) {
			return 1;
		}
		if (start > end) {
			return 0;
		}
		// 首尾相同时,则首尾是回文子序列的一部分length+2,lps(str, start + 1, end - 1)表示去掉下标为start和end后的字符串进行递归的到的最长子序列;
		if (str.charAt(start) == str.charAt(end)) {
			return lps(str, start + 1, end - 1) + 2;
		} else {
			// 首尾不相同时,lps(str, start + 1, end)表示去掉下标为start后的字符串的最长子序列,lps(str, start, end - 1)表示去掉下标为end后的字符串的最长子序列
			return max(lps(str, start + 1, end), lps(str, start, end - 1));
		}
	}

	public static int max(int x, int y) {
		return (x > y) ? x : y;
	}
}

返回最长回文子序列:

package ddd.lps;

public class LPS2 {
	public static void main(String args[]) {
		String string = "ACGTGTCAAAATCG";
		String result = lps(string, 0, string.length() - 1);
		System.out.println("最长回文子序列为:" + result);
		System.out.println("最长回文子序列的长度为:" + result.length());
	}

	public static String lps(String str, int start, int end) {
		if (start == end) {
			return str.charAt(end) + "";
		}
		if (start > end) {
			return "";
		}
		if (str.charAt(start) == str.charAt(end)) {
			return str.charAt(start) + lps(str, start + 1, end - 1) + str.charAt(end);
		} else {
			String right = lps(str, start + 1, end);
			String left = lps(str, start, end - 1);
			int max = max(left.length(), right.length());
			if (max == left.length()) {
				return left;
			} else {
				return right;
			}
		}
	}
	public static int max(int x, int y) {
		return (x > y) ? x : y;
	}
}

转载于:https://my.oschina.net/xleix/blog/817461

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值