最长相同子串

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * @ClassName: Que
 * @Description: 获取两个字符串的最长相同子串,例如abegad与acegab,最大相同子串为ega。
 * @Author: Wanglt
 * @CreateDate: 2020年2月29日
 *
 */
public class Que {

	private String str1;
	private String str2;
	private int[][] temp;

	public Que1(String str1, String str2) {
		this.str1 = str1;
		this.str2 = str2;
		this.temp = new int[str1.length() + 1][str2.length() + 1];
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入字符串A");
		String str1 = scanner.next();
		System.out.println("请输入字符串B");
		String str2 = scanner.next();
//		String str1 = "abceba";
//		String str2 = "bcba";
		Que1 que1 = new Que1(str1, str2);
		System.out.println("最大相同子串:" + que1.LongestSub());
	}

	public String LongestSub() {
		String res = "";
		for (int i = 0; i < str1.length(); i++) {
			for (int j = 0; j < str2.length(); j++) {
				if (str1.charAt(i) == str2.charAt(j)) {
					temp[i + 1][j + 1] = temp[i][j] + 1;
				}
			}
		}
		if (findMax() != null) {
			for (String s : findMax()) {
				res = res + s + " ";
			}
		} else {
			res = "不存在";
		}
		printTemp();
		return res;
	}

	/**
	 * 找最大子串
	 */
	public List<String> findMax() {

		LinkedList<String> list = new LinkedList();
		int[] point = new int[str1.length()];

		String res = "";
		int max = 0;
		int x = 0;
		int y = 0;
		for (int i = 1; i < temp.length; i++) {
			for (int j = 1; j < temp[0].length; j++) {
				if (temp[i][j] > max) {
					max = temp[i][j];
					point = new int[str1.length()];
					point[i - 1] = j - 1;
				} else if (max != 0 && temp[i][j] == max) {
					point[i - 1] = j - 1;
				}
			}
		}
		if (max == 0) {
			return null;
		}
		for (int i = 0; i < point.length; i++) {
			if (point[i] != 0) {
				x = i;
				y = point[i];
				while (temp[x + 1][y + 1] != 0) {
					res = str1.charAt(x) + res;
					x--;
					y--;
				}
				list.add(res);
				res = "";
			}

		}
		return list;
	}

	/**
	 * 输出temp[][]
	 */
	public void printTemp() {
		for (int i = 0; i < temp.length; i++) {
			for (int j = 0; j < temp[0].length; j++) {
				System.out.print(temp[i][j] + " ");
			}
			System.out.println();
		}

	}
}

运行截图:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Letian

您的打赏是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值