using
System;
using
System.Collections.Generic;
class
TrieNode
{
public
int
Val {
get
;
set
; }
public
bool
IsEnding {
get
;
set
; }
public
TrieNode Left {
get
;
set
; }
public
TrieNode Right {
get
;
set
; }
public
TrieNode(
int
val)
{
Val = val;
IsEnding =
false
;
Left =
null
;
Right =
null
;
}
}
class
Program
{
static
void
BuildTree(TrieNode root, List<
string
> nums)
{
foreach
(
var
num
in
nums)
{
TrieNode cur = root;
int
j = 0, len = num.Length;
while
(j < len)
{
if
(num[j] ==
'0'
)
{
if
(cur.Left ==
null
)
{
cur.Left =
new
TrieNode(len - j);
}
else
{
cur.Left.Val = Math.Max(cur.Left.Val, len - j);
}
cur = cur.Left;
}
else
{
if
(cur.Right ==
null
)
{
cur.Right =
new
TrieNode(len - j);
}
else
{
cur.Right.Val = Math.Max(cur.Right.Val, len - j);
}
cur = cur.Right;
}
j++;
}
cur.IsEnding =
true
;
}
}
static
int
MaxDistance(List<
string
> nums)
{
TrieNode root =
new
TrieNode(0);
BuildTree(root, nums);
int
maxDistance = 0;
Queue<TrieNode> queue =
new
Queue<TrieNode>();
queue.Enqueue(root);
while
(queue.Count > 0)
{
TrieNode cur = queue.Dequeue();
if
(cur.Left !=
null
|| cur.Right !=
null
)
{
if
(cur.Left !=
null
&& cur.Right !=
null
)
{
maxDistance = Math.Max(maxDistance, cur.Left.Val + cur.Right.Val);
}
else
if
(cur.IsEnding)
{
maxDistance = Math.Max(maxDistance, cur.Left !=
null
? cur.Left.Val : cur.Right.Val);
}
}
if
(cur.Left !=
null
)
queue.Enqueue(cur.Left);
if
(cur.Right !=
null
)
queue.Enqueue(cur.Right);
}
return
maxDistance;
}
static
void
Main()
{
List<
string
> nums =
new
List<
string
> {
"01011"
,
"010110"
,
"0111"
};
int
maxDistance = MaxDistance(nums);
Console.WriteLine(maxDistance);
}
}