【数据结构与算法】LCS(连续)

今年阿里的笔试题,就有一道是求连续的公共子串。

思路一:我当时第一反应是把其中较短的一个串的所有子串的都求出来,然后用这些子串(先用长度较长的)去长串里面做匹配。后来一想效率太低了。

思路二:效仿不连续的LCS问题,先把表填了,然后再在表里面找。

  • 代码实现

/**
 * 源码名称:LCString.java 
 * 日期:2014-09-02 
 * 程序功能:LCS(连续) 
 * 版权:CopyRight@A2BGeek 
 * 作者:A2BGeek
 */
public class LCString {
	private String mOne, mTwo;
	int[][] mMatrix;
	String mResult;
	int mMaxIndex, mMaxLength;

	public LCString(String one, String two) {
		mOne = one;
		mTwo = two;
		int lengthOne = one.length();
		int lengthTwo = two.length();
		mMatrix = new int[lengthOne + 1][lengthTwo + 1];
		mResult = "";
	}

	public void generateMatrix() {
		int lengthOne = mOne.length();
		int lengthTwo = mTwo.length();
		for (int i = 1; i <= lengthOne; i++) {
			mMatrix[i][0] = 0;
		}
		for (int j = 1; j <= lengthTwo; j++) {
			mMatrix[0][j] = 0;
		}
		mMatrix[0][0] = 0;
		for (int i = 1; i <= lengthOne; i++) {
			for (int j = 1; j <= lengthTwo; j++) {
				if (mOne.charAt(i - 1) == mTwo.charAt(j - 1)) {
					mMatrix[i][j] = mMatrix[i - 1][j - 1] + 1;
				} else {
					mMatrix[i][j] = 0;
				}
				if (mMatrix[i][j] > mMaxLength) {
					mMaxLength = mMatrix[i][j];
					mMaxIndex = i;
				}
			}
		}
	}

	public void getLCString() {
		for (int i = 0; i < mMaxLength; i++) {
			mResult += mOne.charAt(mMaxIndex - 1 - mMaxLength + 1 + i);
		}
	}

	public static void main(String[] args) {
		String one = "abgfcdeij";
		String two = "knkcdefdg";
		LCString lcString = new LCString(one, two);
		lcString.generateMatrix();
		lcString.getLCString();
		System.out.println(lcString.mResult);
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值