算法——求公共子序列的长度

版权声明:版权声明:转载必须注明本文转自StathamJ的博客:https://blog.csdn.net/qq_41664447 https://blog.csdn.net/qq_41664447/article/details/88771719

问题

求两个串的最大公共子序列的长度。(子串不可间隔,子序列可间隔)
eg:

  • 输入:abcdef xacdg
  • 输出:3

思路

首先将该任务进行划分,划分成两种情况:

  • 第一个字符相等的情况:将两个去掉首字符的字符串,继续传入递归然后加1。
  • 第一个字符不相等的情况:s2不变并去掉s1的首字符继续递归,s1不变并去掉s2的首字符继续递归,然后判断两个递归哪一个返回值最大。

实现代码

package suanfa;

public class sonlist{
	public static int f(String s1,String s2)
	{
		if(s1.length()==0||s2.length()==0)
			return 0;
		if(s1.charAt(0)==s2.charAt(0)) //首字符相等时
			return f(s1.substring(1),s2.substring(1))+1;
		else //首字符不相等时
			return Math.max(f(s1.substring(1),s2), f(s1,s2.substring(1)));
	}
	public static void main(String[] args) {
		int k=f("abcdef","xacdg");
		System.out.println(k);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41664447/article/details/88771719