试题 算法训练 字串统计 java 题解

问题描述

  给定一个长度为n的字符串S,还有一个数字L,统计长度大于等于L的出现次数最多的子串(不同的出现可以相交),如果有多个,输出最长的,如果仍然有多个,输出第一次出现最早的。

输入格式

  第一行一个数字L。
  第二行是字符串S。
  L大于0,且不超过S的长度。

输出格式

一行,题目要求的字符串。

输入样例1:
4
bbaabbaaaaa

输出样例1
bbaa

输入样例2:
2
bbaabbaaaaa

输出样例2:

aa

数据规模和约定

n<=60
S中所有字符都是小写英文字母。

提示

枚举所有可能的子串,统计出现次数,找出符合条件的那个

解题思路:

用子串作key,类作value,排序的顺序依次为三步:次数最多的,长度最长的,第一次出现最早的,一定要看清题!!!

java代码:

import java.io.*;
import java.util.*;

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		String str = br.readLine();
		HashMap<String,temp87> map = new HashMap<>();
		int len = str.length();
		int num = 1;
		List<temp87> list = new ArrayList<>();
		for(int i = 0; i <= len - n;i++) {
			for(int j = i + n;j <= len;j++) {
				String s = str.substring(i, j);
				temp87 value = map.get(s);
				if(value == null) {
					temp87 temp = new temp87(s, 1, num);
					map.put(s, temp);
					num++;
					list.add(temp);
				}else {
					value.n = value.n + 1;
				}
			}
		}
		Collections.sort(list);
		System.out.println(list.get(0).s);
	}
}
class temp87 implements Comparable<temp87>{
	String s;
	Integer n;
	int num;
	int length;
	
	public temp87(String s, int n, int num) {
		this.s = s;
		this.n = n;
		this.num = num;
		length = s.length();
	}

	@Override
	public int compareTo(temp87 o) {
		if(this.n != o.n) {
			return o.n - this.n;
		}else if(this.length != o.length){
			return o.length - this.length;
		}else {
			return this.num - o.num;
		}
	}
}

提交截图:

Guess you like

Origin blog.csdn.net/weixin_48898946/article/details/121056154