diff --git a/30. Substring with Concatenation of All Words/Solution.cs b/30. Substring with Concatenation of All Words/Solution.cs index 2ec9574..afabd4d 100644 --- a/30. Substring with Concatenation of All Words/Solution.cs +++ b/30. Substring with Concatenation of All Words/Solution.cs @@ -1,35 +1,34 @@ -public class Solution { - public IList FindSubstring(string s, string[] words) { +public class Solution +{ + public IList FindSubstring(string s, string[] words) + { var len = words[0].Length; - var allLen = len*words.Length; + var allLen = len * words.Length; var dict = new Dictionary(); - foreach(var word in words) + foreach (var word in words) { dict.TryAdd(word, 0); dict[word]++; } var answer = new List(); - var dictClone = new Dictionary(dict); - for(var i = 0; i < s.Length-allLen+1; i++) + var windowDict = new Dictionary(); + 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++; - } - else - { - break; + var leftWord = s[prevInx..(prevInx + len)]; + windowDict[leftWord]--; } + 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; }