求一个字符串最长重复子串(Java版)

例如:
例如字符串 s =“abcdeabc”
输出:abc

为何选用后缀?
后缀字符串的前缀包含了字符串S的部分子串,只要求出字符串S的所有后缀就可间接的表示了S所有的子串

解题思路

保存s字符串的所有后缀
对所有后缀进行排序(自然排序)
比较排序后的相邻的后缀的最长公共子串(两个后缀从第一个字符开始的就相等得到公共子串),求出最长的公共子串**

public class Main{
    //保存最长公共子串
	static String result = "";
	public static void main(String [] args) throws InterruptedException {
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		ArrayList<String> list = new ArrayList<String>();
		//得到字符串的所有后缀
		for(int i = s.length()-1;i>=0;i--) {
			list.add(s.substring(i));
		}
		Collections.sort(list);
		int maxLen = 0;
		for(int i = 0;i<s.length()-1;i++) {
			int len = getComlen(list.get(i),list.get(i+1));
			maxLen = Math.max(maxLen, len);
		}
		System.out.println(result+":"+maxLen);
    }
    //得到两个字符串最长公共长度
	public static int getComlen(String str1,String str2) {
		int i;
		for(i =0;i<str1.length()&&i<str2.length();i++) {
			if(str1.charAt(i)!=str2.charAt(i)) {
				break;	
			}
		}
		String temp = str1.substring(0,i);
		if(temp.length()>result.length()) result = temp;
		return i;
	}
	
}
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值