Вот функция «Longest Common Substring» для двух строк в PowerShell (на основе викибук C # пример ):
Function get-LongestCommonSubstring
{
Param(
[string]$String1,
[string]$String2
)
if((!$String1) -or (!$String2)){Break}
# .Net Two dimensional Array:
$Num = New-Object 'object[,]' $String1.Length, $String2.Length
[int]$maxlen = 0
[int]$lastSubsBegin = 0
$sequenceBuilder = New-Object -TypeName "System.Text.StringBuilder"
for ([int]$i = 0; $i -lt $String1.Length; $i++)
{
for ([int]$j = 0; $j -lt $String2.Length; $j++)
{
if ($String1[$i] -ne $String2[$j])
{
$Num[$i, $j] = 0
}else{
if (($i -eq 0) -or ($j -eq 0))
{
$Num[$i, $j] = 1
}else{
$Num[$i, $j] = 1 + $Num[($i - 1), ($j - 1)]
}
if ($Num[$i, $j] -gt $maxlen)
{
$maxlen = $Num[$i, $j]
[int]$thisSubsBegin = $i - $Num[$i, $j] + 1
if($lastSubsBegin -eq $thisSubsBegin)
{#if the current LCS is the same as the last time this block ran
[void]$sequenceBuilder.Append($String1[$i]);
}else{ #this block resets the string builder if a different LCS is found
$lastSubsBegin = $thisSubsBegin
$sequenceBuilder.Length = 0 #clear it
[void]$sequenceBuilder.Append($String1.Substring($lastSubsBegin, (($i + 1) - $lastSubsBegin)))
}
}
}
}
}
return $sequenceBuilder.ToString()
}
Чтобы использовать это для более чем двух строк, используйте это так:
Function get-LongestCommonSubstringArray
{
Param(
[Parameter(Position=0, Mandatory=$True)][Array]$Array
)
$PreviousSubString = $Null
$LongestCommonSubstring = $Null
foreach($SubString in $Array)
{
if($LongestCommonSubstring)
{
$LongestCommonSubstring = get-LongestCommonSubstring $SubString $LongestCommonSubstring
write-verbose "Consequtive diff: $LongestCommonSubstring"
}else{
if($PreviousSubString)
{
$LongestCommonSubstring = get-LongestCommonSubstring $SubString $PreviousSubString
write-verbose "first one diff: $LongestCommonSubstring"
}else{
$PreviousSubString = $SubString
write-verbose "No PreviousSubstring yet, setting it to: $PreviousSubString"
}
}
}
Return $LongestCommonSubstring
}
get-LongestCommonSubstringArray $Arr -verbose