连续字母长度

标题:连续字母长度 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
给定一个字符串,只包含大写字母,求在包含同一字母的子串中,长度第 k 长的子串的长度,相同字母只取最长的那个子串。


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine().trim();
        int k = Integer.parseInt(sc.nextLine().trim());
        int index = 0;
        HashMap<Character, Integer> hs = new HashMap<>();
        while (index < s.length()) {
            char c = s.charAt(index);
            int count = 1;
            while (index < s.length()-1 && s.charAt(index+1) == s.charAt(index)) {
                count++;
                index++;
            }
            if (!hs.containsKey(c)) {
                hs.put(c, count);
            } else {
                if (hs.get(c) < count) {
                    hs.put(c, count);
                }
            }
            index++;
        }
        List<Character> lst = new ArrayList<>(hs.keySet());
        lst.sort((c1, c2) -> {
            return hs.get(c2) - hs.get(c1);
        });
        if (k > lst.size() || lst.size() == 0 || k <= 0) {
            System.out.println(-1);
        } else {
            System.out.println(hs.get(lst.get(k-1)));
        }
    }
}
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
	string str;
	int k;
	cin >> str >> k;
	set<char> sc{ str.begin(), str.end() };


	vector<int> vecLen;
	if (sc.size() < k || k <= 0)
	{
		cout << -1 << endl;
		return 0;
	}
	for (auto c:sc)
	{
		int count = 1;
		int maxCnt = count;
		for (int i=0;i<str.size();i++)
		{
			if (i+1 < str.size() && str[i] == str[i+1] && str[i] == c)
			{
				count++;
				if (count > maxCnt)
				{
					maxCnt = count;
				}
			}
			else
			{
				count = 1;
			}
		}
		vecLen.push_back(maxCnt);
	}
	sort(vecLen.begin(), vecLen.end());
	reverse(vecLen.begin(), vecLen.end());
	cout << vecLen[k-1] << endl;
	return 0;
}



全部评论

相关推荐

虽然大家都在劝退读研,说读研以后也是打工,不如本科直接去打工,但随着现在研究生越来越多,很多企业招聘要求就会变成研究生起招,本科投递简历就会被卡,横向比较时也会因为"本科学历比不上研究生学历"被筛掉,而且你没发现劝退读研的基本都是读完研的人吗?而且进体制、国企等,研究生也比本科生升的快,他们拿着研究生文凭劝你一个本科生,可别当真了
球1个offer:每个行业都是不一定的,例如计算机开发岗,只要是92学历,完全可以冲互联网大厂,没进去抛开运气因素,就是不够努力,准备的晚没有实习等等。计算机算法岗还是要读研的,研究生是基本要求。现在太多人无脑考研了,因为本科秋招春招啥都没准备过,只能读研
点赞 评论 收藏
分享
04-27 08:59
常州大学 Java
牛客139242382号:《两门以上汇编语言》
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务