This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
StringInterleaving.cs
58 lines (47 loc) · 1.55 KB
/
StringInterleaving.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CS.Problems
{
/// <summary>
/// Problem details below
/// http://www.geeksforgeeks.org/check-whether-a-given-string-is-an-interleaving-of-two-other-given-strings-set-2/
/// </summary>
public class StringInterleaving
{
public static bool IsInterleaved(string a, string b, string c)
{
if (a.Length + b.Length != c.Length)
return false;
return IsInterleaved(a, b, c,
a.Length - 1, b.Length - 1, c.Length - 1,
new Dictionary<string, bool>());
}
public static bool IsInterleaved(string a, string b, string c,
int aIndex, int bIndex, int cIndex, Dictionary<string, bool> cache)
{
var cacheKey = $"{aIndex}-{bIndex}-{cIndex}";
if(cache.ContainsKey(cacheKey))
{
return cache[cacheKey];
}
if (cIndex == -1)
{
return true;
}
var result = false;
if (aIndex >= 0 && c[cIndex] == a[aIndex])
{
result = IsInterleaved(a, b, c, aIndex - 1, bIndex, cIndex - 1, cache);
}
if (bIndex >= 0 && c[cIndex] == b[bIndex])
{
result = result || IsInterleaved(a, b, c, aIndex, bIndex - 1, cIndex - 1, cache);
}
cache.Add(cacheKey, result);
return result;
}
}
}