1. 程式人生 > 其它 >Longest Substring with K Distinct Characters (medium)

Longest Substring with K Distinct Characters (medium)

技術標籤:leetcode刷題# 1. Pattern: Sliding window

刷題參考: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;
}