Longest Substring with K Distinct Characters (medium)

本文介绍了一种使用C++解决字符串问题的方法,针对给定字符串s,找到包含最多k个不同字符的最长子串长度。通过维护一个字符映射并动态调整起始位置,确保子串中字符数量不超过k。实例代码和详细步骤有助于理解算法原理。
摘要由CSDN通过智能技术生成

刷题参考:https://blog.csdn.net/IBelieve2016/article/details/104544763 

#include<iostream>
#include<vector>
#include <unordered_map>
#include<string>
using namespace std;
/*
Given a string, find the length of the longest substring T 
that contains at most k distinct characters.
包含k个不同字符的最长子串 

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.

用一个start纪录字符串开始的位置 
charmap:纪录当前是否已经出现字符 ,(具有去重的作用) 
统计charmap个数,即从start至当前位置具有多少个不同字符。
max(res,i-start+1)
*/ 
int solution(string s,int k){
	int start=0,res=0;
	unordered_map<char,int> charmap;
	for(int i=0;i<s.size();i++){
		//纪录当前存在的字符以及频数
		charmap[s[i]]++;
		//当不同字符的数量大于k,则移动start 
		while(charmap.size()>k){
			//start位置的值在hash中值的频数-1 
			charmap[s[start]]--;
			//如果等于0则将该值移除 
			if(charmap[s[start]]==0){
				charmap.erase(s[start]);
			}
			start++;
		}
		res=max(res,i-start+1);
	}
	return res;
}

int main(){
	string s="eceba";
	int k=2;
	
	cout<<solution(s,k);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值