Оптимально

This commit is contained in:
2026-03-26 00:22:10 +03:00
parent 4681660c8c
commit 3f3bc52106

View File

@@ -1,5 +1,7 @@
public class Solution {
public IList<int> FindSubstring(string s, string[] words) {
public class Solution
{
public IList<int> FindSubstring(string s, string[] words)
{
var len = words[0].Length;
var allLen = len * words.Length;
var dict = new Dictionary<string, int>();
@@ -9,27 +11,24 @@ public class Solution {
dict[word]++;
}
var answer = new List<int>();
var dictClone = new Dictionary<string, int>(dict);
for(var i = 0; i < s.Length-allLen+1; i++)
var windowDict = new Dictionary<string, int>();
for (var offset = 0; offset < len; offset++)
{
var valid = 0;
foreach (var kvp in dictClone)
dictClone[kvp.Key] = dict[kvp.Key];
for(var j=i; j < i+allLen; j+=len)
for (var i = offset; i <= s.Length-len; i += len)
{
var word = s[j..(j+len)];
if(dictClone.TryGetValue(word, out var count) && count > 0)
var word = s[i..(i + len)];
var prevInx = i - allLen;
if (prevInx >= 0)
{
dictClone[word]--;
valid++;
var leftWord = s[prevInx..(prevInx + len)];
windowDict[leftWord]--;
}
else
{
break;
windowDict.TryAdd(word, 0);
windowDict[word]++;
if (dict.All(kvp => windowDict.TryGetValue(kvp.Key, out var count) && count == kvp.Value))
answer.Add(prevInx + len);
}
}
if(valid == words.Length)
answer.Add(i);
windowDict.Clear();
}
return answer;
}