30. Substring with Concatenation of All Words
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>_30._Substring_with_Concatenation_of_All_Words</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
18
30. Substring with Concatenation of All Words/Program.cs
Normal file
18
30. Substring with Concatenation of All Words/Program.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
var sol = new Solution();
|
||||
|
||||
var cases = new (string s, string[] words, int[] expected)[]
|
||||
{
|
||||
// ("barfoothefoobarman", new[] { "foo", "bar" }, new[] { 0, 9 }),
|
||||
// ("wordgoodgoodgoodbestword", new[] { "word", "good", "best", "word" }, Array.Empty<int>()),
|
||||
// ("barfoofoobarthefoobarman", new[] { "bar", "foo", "the" }, new[] { 6, 9, 12 }),
|
||||
("wordgoodgoodgoodbestword", new[] { "word", "good", "best", "good" }, new[] { 8 })
|
||||
};
|
||||
|
||||
string Format(IEnumerable<int> values) => $"[{string.Join(",", values)}]";
|
||||
string FormatWords(IEnumerable<string> values) => $"[{string.Join(",", values)}]";
|
||||
|
||||
foreach (var (s, words, expected) in cases)
|
||||
{
|
||||
var actual = sol.FindSubstring(s, words);
|
||||
Console.WriteLine($"{s} | {FormatWords(words)} -> {Format(actual)} (expected: {Format(expected)})");
|
||||
}
|
||||
36
30. Substring with Concatenation of All Words/Solution.cs
Normal file
36
30. Substring with Concatenation of All Words/Solution.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user