使用哈希 C++ 查找具有 k 个不同/唯一字符的最长子字符串
finding the longest substring with k different/unique characters using hash c++
我遇到了找到具有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
相关文章:
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 检查字符串是否仅包含使用.at(int)的唯一字符
- 生成唯一的随机字符并将其保存在数组中
- 使用哈希 C++ 查找具有 k 个不同/唯一字符的最长子字符串
- 检查字符串是否具有C++中的所有唯一字符
- 如何调整属于类的唯一指针的字符数组的大小.它必须在程序的整个生命周期中保持活力
- 字符是唯一具有强制大小的类型
- 计算数组中唯一字符的函数
- 唯一的字符代码在 Linux 中运行时不起作用,但在 Windows (C++) 中很好
- 输出对象中唯一字符的数量
- 给定一个字符串,我如何才能只添加另一个字符串中的唯一字符
- 确定std::string是否具有所有唯一字符[C++]
- c++唯一字符检查
- 实现O(n)算法来确定字符串是否所有字符都是唯一的
- 从字符串中删除两个字符以获得唯一字符的可能性
- 使用Unordered_map在c++中创建字符串中的第一个唯一字符
- 检查字符串是否有唯一字符
- 有人能解释一下这个程序来检查字符串中的唯一字符吗?
- 字符数组是唯一具有某种形式的null终止的类型吗
- 在c++中,判断unicode字符字符串是否具有唯一字符的最有效方法是什么?