字符串中出现的相同且长度最长的字符串

package com.a.b;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StringAnalysis {
	public static void main(String[] args) {
		String s = null;// "   ";// " bcbccccc";// null;//"yyabcdabjcabceg";
		find(s);
	}

	private static String commonStart(String thisOne, String another) {
		int length1 = thisOne.length();
		int length2 = another.length();
		int j = 0;
		for (; j < length1 && j < length2
				&& (thisOne.charAt(j) == another.charAt(j)); j++) {
		}
		return thisOne.substring(0, j);
	}

	private static void find(String s) {
		if (null == s) {
			System.out.println("s==null");
			return;
		}
		int length = s.length();
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < length; i++) {
			list.add(s.substring(i));
		}
		Collections.sort(list);
		int max = 0;
		int maxIndex = -1;
		for (int i = 0; i < length - 1; i++) {
			String node = list.get(i);
			String next = list.get(i + 1);
			String common = commonStart(node, next);
			if (common.length() > max) {
				max = common.length();
				maxIndex = i;
			}
		}
		if (maxIndex >= 0) {
			String common = list.get(maxIndex).substring(0, max);
			System.out.println(common + "#" + (s.indexOf(common) + 1));
		} else {
			System.out.println("not found.");
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值