![](/img/trans.png)
[英]Where is the flaw in my algorithm to find the size of smallest substring containing an exact character set?
[英]Does there exist an O(n) algorithm for finding the smallest substring from an input string, containing a given character set and count?
給定一個字符串s
和一組帶count的字符,找到s
中包含所有重復其計數次數的所有字符的最小子字符串。
例:
charcount = { { 'A', 3 }, { 'B', 1 } };
str = "kjhdfsbabasdadaaaaasdkaaajbajerhhayeom"
---> "aajba"
我知道如何在O(n^2)
時間內通過從最小到最大的所有子字符串進行迭代來實現。
功能可能的簽名:
string SmallestSubstringWithCharacterCount(Dictionary<char,int> chardic, string source)
{
// ...
}
我猜有某種方法可以遍歷str
因為一旦到達
"kjhdfsbabasdadaaaaasdkaaajbajerhhayeom"
|
here
您將找到第一個字符串"kjhdfsbabasda"
,其中包含集合中的所有字符。
是的,確實存在線性算法。
您需要使用初始零計數和GoodCount計數器設置其他currentcharcount。
創建兩個索引指針-左和右,然后將它們在輸入字符串中移動。
如果下一個字符來自集合,則此字符在currentcharcount中的增量計數。 如果此計數等於目標值,則遞增GoodCount。 向右移動索引,直到GoodCount達到字符數長度-現在,當前子字符串包含所有需要的字符。
然后,向左移動索引,減少計數,並在需要時減少GoodCount。 就在此步驟之前,我們從這里開始有最短的子字符串。
遞減GoodCount之后-用正確的索引重復該過程,依此類推,以從所有最短的子字符串中選擇最佳的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.