长度小于3的连续子串在原串中出现的次数,结果按照数量和字典排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class StringCount {

	private static int MAXLENGTH = 3;
	public static void main(String[] args) {
		String s = "cccdaaaaaabbbb";
		new StringCount().count(s);
	}

	private static Map<String, Integer> map = new HashMap<String, Integer>();

	void count(String s) {
		for (int i = 1; i < =MAXLENGTH; i++) {
			countStr(i, s);
		}
		sort();
	}

	private void countStr(int len, String s) {
		for (int i = 0; i + len <= s.length(); i++) {
			String temp = s.substring(i, i + len);
			if (map.get(temp) == null) {
				countStr1(temp, s);
			} else {
				continue;
			}
		}
	}

	private void countStr1(String temp, String s) {
		if (null == map.get(temp))
			map.put(temp, 0);
		else
			return;
		while (s != null && !s.equals("")) {
			if (s.startsWith(temp)) {
				int t = map.get(temp);
				map.put(temp, ++t);
			}
			s = s.substring(1);
		}
	}

	static void sort() {
		List<Entry<String, Integer>> mappingList = new ArrayList<Map.Entry<String, Integer>>(
				map.entrySet());

		// 通过比较器实现比较排序
		Collections.sort(mappingList,
				new Comparator<Map.Entry<String, Integer>>() {
					public int compare(Map.Entry<String, Integer> entry1,
							Map.Entry<String, Integer> entry2) {
						if (entry1.getValue() == entry2.getValue()) {
							return entry1.getKey().compareTo(entry2.getKey());
						} else {
							return entry2.getValue().compareTo(
									entry1.getValue());
						}
					}
				});
		for (Map.Entry<String, Integer> mapping : mappingList) {
			System.out.println(mapping.getKey() + ":" + mapping.getValue());
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值