![](/img/trans.png)
[英]Does there exist an O(n) algorithm for finding the smallest substring from an input string, containing a given character set and count?
[英]Where is the flaw in my algorithm to find the size of smallest substring containing an exact character set?
設置是我有一個字符串
s = "GAAATAAA"
和一本字典一樣
surpdic = { 'A' -> 4 }
字典的含義是s
有4
剩余的A
字符。
什么我的算法試圖找到的是最小的子串的大小s
包含4
A
秒。 我無法弄清楚為什么它不能處理所有的測試用例。
它應該像工作一樣
GAAATAAA
||| |||
i|| j|| j - i = 4, mindiff = 4
|| ||
i| j| j - i = 4, mindiff = 4
| |
i j j - i = 4, mindiff = 4
在我提供的例子上。 換句話說,在字符串中從左到右,找到包含所有字符的第一個跨度,然后有效地取出左指針並將其移動到下一個可能跨度的開頭; 一直跟蹤最小跨度。
int mindiff = Int32.MaxValue;
int left = 0;
while(!surpdic.ContainsKey(s[left++]));
for(int right = left; right < s.Length; ++right)
{
if(surpdic.ContainsKey(s[right]))
surpdic[s[right]] -= 1;
if(surpdic.Values.All(count => count == 0))
{
int diff = right - left;
if(diff < mindiff)
mindiff = diff;
surpdic[s[left]] += 1;
while(!surpdic.ContainsKey(s[left++]));
}
}
編輯:所以這是一個給我一個運行時錯誤的情況。
using System.IO;
using System.Linq;
using System.Text;
using System;
using System.Collections.Generic;
public class Solution
{
static int SmallestSubstringContainingChars(string source, Dictionary<char,int> surpdic)
{
int mindiff = Int32.MaxValue;
int left = 0;
while(!surpdic.ContainsKey(source[left++]));
for(int right = left; right < source.Length; ++right)
{
if(surpdic.ContainsKey(source[right]))
surpdic[source[right]] -= 1;
if(surpdic.Values.All(count => count == 0))
{
int diff = right - left;
if(diff < mindiff)
mindiff = diff;
surpdic[source[left]] += 1;
while(!surpdic.ContainsKey(source[left++]));
}
}
return mindiff + 1;
}
public void Main(string[] args)
{
string s = "ACTGATTT";
Dictionary<char,int> d = new Dictionary<char,int>() { { 'A' , 1 }, { 'T' , 3 } };
Console.WriteLine( SmallestSubstringContainingChars(s,d));
}
}
我在你的代碼中發現了很多問題。
首先是你向左遞增的方式。
此外,您正在修改字典,因此下一次執行將以錯誤的字典開頭,這就是我創建副本的原因。
如果字典條目的值已經為0,請不要遞減字典條目,否則您的All
代碼將無效。
檢查下面的代碼,如果您不明白,請在下面評論。 如果找不到所需的模式,它將返回-1:
static int SmallestSubstringContainingChars(string source, Dictionary<char, int> surpdic)
{
int mindiff = -2;
int left = 0;
while (left<source.Length)
{
if (surpdic.ContainsKey(source[left]))
{
Dictionary<char, int> md = new Dictionary<char, int>(surpdic);
md[source[left]] -= 1;
for (int right = left; right < source.Length; ++right)
{
if (md.ContainsKey(source[right]) && md[source[right]]>0)
md[source[right]] -= 1;
if (md.Values.All(count => count == 0))
{
int diff = right - left;
if (mindiff==-2 || diff < mindiff)
mindiff = diff;
}
}
}
left++;
}
return mindiff + 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.