using
System;
using
System.Collections.Generic;
class
TrieNode {
public
TrieNode[] Children;
public
bool
IsEndOfWord;
public
TrieNode()
{
Children =
new
TrieNode[26];
IsEndOfWord =
false
;
}
}
class
Trie {
private
TrieNode root;
private
TrieNode GetNode() {
return
new
TrieNode(); }
private
int
CharToIndex(
char
ch) {
return
ch -
'a'
; }
public
Trie() { root = GetNode(); }
public
void
Insert(
string
key)
{
TrieNode word = root;
int
length = key.Length;
for
(
int
level = 0; level < length; level++) {
int
index = CharToIndex(key[level]);
if
(word.Children[index] ==
null
) {
word.Children[index] = GetNode();
}
word = word.Children[index];
}
word.IsEndOfWord =
true
;
}
public
bool
Search(
string
key)
{
TrieNode word = root;
int
length = key.Length;
int
level = 0;
while
(level < length) {
int
index = CharToIndex(key[level]);
if
(word.Children[index] ==
null
) {
return
false
;
}
word = word.Children[index];
level++;
}
return
(level == length);
}
public
static
List<Tuple<
int
,
int
> >
BuildViaSubstrings(
string
P,
string
Q)
{
if
(P.Length == 1) {
for
(
int
i = 0; i < Q.Length; i++) {
if
(Q[i] != P[0]) {
return
new
List<Tuple<
int
,
int
> >();
}
}
List<Tuple<
int
,
int
> > substrings
=
new
List<Tuple<
int
,
int
> >();
for
(
int
i = 0; i < Q.Length; i++) {
substrings.Add(
new
Tuple<
int
,
int
>(0, i));
}
return
substrings;
}
else
{
Trie x =
new
Trie();
for
(
int
i = 0; i < P.Length; i++) {
x.Insert(P.Substring(i));
}
int
startPos = 0;
List<Tuple<
int
,
int
> > substrings
=
new
List<Tuple<
int
,
int
> >();
bool
y =
true
;
int
k = 1;
while
(k <= Q.Length) {
y = x.Search(
Q.Substring(startPos, k - startPos));
if
(!y) {
if
(k == startPos + 1) {
return
new
List<Tuple<
int
,
int
> >();
}
else
{
string
sub = Q.Substring(
startPos, k - 1 - startPos);
int
lt = sub.Length;
int
m = P.IndexOf(sub);
substrings.Add(
new
Tuple<
int
,
int
>(
m, m + lt - 1));
startPos = k - 1;
k = k - 1;
y =
true
;
}
}
else
if
(y && k == Q.Length) {
string
sub = Q.Substring(startPos);
int
lt = sub.Length;
int
m = P.IndexOf(sub);
substrings.Add(
new
Tuple<
int
,
int
>(m, m + lt - 1));
}
k++;
}
if
(y && substrings.Count == 0) {
return
new
List<Tuple<
int
,
int
> >{
new
Tuple<
int
,
int
>(P.IndexOf(Q),
Q.Length - 1)
};
}
else
{
return
substrings;
}
}
}
}
class
GFG {
static
void
Main(
string
[] args)
{
string
str1 =
"ssrtssr"
;
string
str2 =
"rsstsr"
;
List<Tuple<
int
,
int
> > ans
= Trie.BuildViaSubstrings(str1, str2);
foreach
(
var
p
in
ans)
{
Console.Write(
"("
+ p.Item1 +
", "
+ p.Item2
+
") "
);
}
Console.WriteLine();
}
}