-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path030-SubstringWithConcatenationOfAllWords.cs
72 lines (62 loc) · 2.1 KB
/
030-SubstringWithConcatenationOfAllWords.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//-----------------------------------------------------------------------------
// Runtime: 828ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _030_SubstringWithConcatenationOfAllWords
{
public IList<int> FindSubstring(string s, string[] words)
{
var result = new List<int>();
var wordsLenght = words.Length;
var sLenght = s.Length;
if (sLenght == 0 || wordsLenght == 0) { return result; }
var wordLenght = words[0].Length;
var concatLenght = wordsLenght * wordLenght;
if (concatLenght > sLenght) { return result; }
var wordsMap = new Dictionary<string, int>();
foreach (var word in words)
{
if (wordsMap.ContainsKey(word))
{
wordsMap[word]++;
}
else
{
wordsMap[word] = 1;
}
}
IDictionary<string, int> used;
int i, j, count;
var subString = string.Empty;
bool allUsed = false;
for (i = 0; i <= sLenght - concatLenght; i++)
{
used = new Dictionary<string, int>(wordsMap);
for (j = i; j <= sLenght - wordLenght; j += wordLenght)
{
subString = s.Substring(j, wordLenght);
if (used.TryGetValue(subString, out count))
{
if (count == 0) { break; }
used[subString]--;
}
else
{
break;
}
}
allUsed = true;
foreach (var pair in used)
{
if (pair.Value > 0) { allUsed = false; break; }
}
if (allUsed) { result.Add(i); }
}
return result;
}
}
}