使用哈希 C++ 查找具有 k 个不同/唯一字符的最长子字符串

finding the longest substring with k different/unique characters using hash c++

本文关键字:字符 唯一 字符串 C++ 哈希 查找      更新时间:2023-10-16

我遇到了找到具有k个唯一字符的最长子字符串的问题。例如,给定以下str=abcbbbddcc,结果应为:

  • k=2 => bcbbb
  • k=3 => bcbbbddcc

为此,我使用哈希表创建了一个函数。哈希表将充当搜索窗口。每当当前窗口中的唯一字符超过 k 个时,我都会通过将窗口的当前"开始"向右移动来缩小它。否则,我只是扩展窗口的大小。不幸的是,这似乎是我的代码上的错误,但我仍然找不到它。任何人都可以帮我找到问题吗?我的函数的输出是子字符串的开始索引及其长度,即 substring(start, start+maxSize); .我找到了一些相关的帖子java-sol和python-sol,但仍然没有使用哈希表的基于C++的解决方案。

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
typedef std::vector<int> vector;
typedef std::string string;
typedef std::unordered_map<char, int> unordered_map;
typedef unordered_map::iterator map_iter;
vector longestSubstring(const string & str, int k){
    if(str.length() == 0 || k < 0){
        return {0};
    }
    int size = str.length();
    int start = 0;
    unordered_map map;
    int maxSize = 0;
    int count = 0;
    char c;
    for(int i = 0; i < size; i++){
        c = str[i];
        if(map.find(c)!=map.end()){
            map[c]++;
        }
        else{
            map.insert({c, 1});
        }
        while(map.size()>k){
            c = str[start];
            count = map[c];
            if(count>1){
                map[c]--;
            } 
            else{
                map.erase(c);
            }
            start++;
        }
        maxSize = std::max(maxSize, i-start+1);
    }
    return {start, maxSize};
}

maxSize = std::max(maxSize, i-start+1);之前,必须确保映射大小正好k - 您永远无法达到k但当前代码会不断更新maxSize

还要记住自己的max代码中的start

    if (map.size() == k) 
        if (i - start + 1 > maxSize) {
            maxSize = i - start + 1;
            astart = start;
        }
...
return {astart, maxSize};

Ideone check