题目 1619: 蓝桥杯算法训练VIP-字串统计

题目描述:

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

代码:

package lanqiao;

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int L = sc.nextInt();
        sc.nextLine();
        String s = sc.nextLine();
        s.trim();

        int max = 1;
        Map<String,Integer> map = new LinkedHashMap<String,Integer>();

        for(int i = 0;i < s.length();i ++)
        {
            for(int j = i + L;j <= s.length();j ++)
            {
                //截取对应的字符串
                String s2 = s.substring(i,j);

                if(map.containsKey(s2))
                {
                    int size = map.get(s2) + 1;
                    map.put(s2,size);

                    max = Math.max(max,size);
                }
                else{
                    map.put(s2,1);
                }
            }
        }

        int count = 0;
        int longs = 0;
        String ans = "";

        for(String s1:map.keySet())
        {
            if(map.get(s1) == max)
            {
                count ++;
                longs = Math.max(longs,s1.length());
                ans = s1;
            }
        }

        if(count == 1)
        {
            System.out.println(ans);
        }
        else{
            for(String s1:map.keySet())
            {
                if(map.get(s1) == max && s1.length() == longs)
                {
                    System.out.println(s1);
                    break;
                }
            }
        }

    }
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

几两春秋梦_

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值