30. Substring with Concatenation of All Words

This commit is contained in:
2026-03-25 23:58:01 +03:00
parent 6b483ea6d1
commit 4681660c8c
5 changed files with 80 additions and 1 deletions

View File

@@ -0,0 +1,36 @@
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>();
foreach(var word in words)
{
dict.TryAdd(word, 0);
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 valid = 0;
foreach (var kvp in dictClone)
dictClone[kvp.Key] = dict[kvp.Key];
for(var j=i; j < i+allLen; j+=len)
{
var word = s[j..(j+len)];
if(dictClone.TryGetValue(word, out var count) && count > 0)
{
dictClone[word]--;
valid++;
}
else
{
break;
}
}
if(valid == words.Length)
answer.Add(i);
}
return answer;
}
}