Powershell,134个字节
param($m,$c)$c-csplit"([$m])"|%{$i+=$o=$_-ceq$m[+$i]
if($o-or$_-cne"`0$h"[-1]){$h+=($_-replace'(.)(?=\1)')*($o+1)}}
$h*!($i-$m.Length)
empty string
如果载体未按正确的顺序包含消息字符,则脚本返回。
少打高尔夫的测试脚本:
$f = {
param($message,$carrier)
$carrier-csplit"([$message])"|%{ # split by chars of the message, chars itself included ([])
$offset=$_-ceq$message[+$i] # 0 or 1 if current substring is a current message char (case-sensitive equality)
$i+=$offset # move to next message char if need it
if($offset-or$_-cne"`0$h"[-1]){ # condition to remove redundant doubles after message char: arrrived -> arrived, ooo -> oo, etc
# `0 to avoid exception error if $h is empty
$h+=($_-replace'(.)(?=\1)')*($offset+1) # accumulate a double message char or a single substring without inner doubles: arried -> arived, anna -> ana, etc
}
}
$h*!($i-$message.Length) # repeat 0 or 1 times to return '' if the carrier does not contain the message characters in the right order
}
@(
,('hi' ,'has it arrived?' ,'hhas iit arived?', 'hhas it ariived?')
,('hi?' ,'has it arrived?' ,'hhas iit arived??', 'hhas it ariived??')
,('sir' ,'has it arrived?' ,'hass iit arrived?')
,('foo' ,'has it arrived?' ,'')
,('Car' ,'Cats are cool.' ,'CCaats arre col.')
,('car' ,'Cats are cool.' ,'')
,('Couch' ,'Couch' ,'CCoouucchh')
,('oo' ,'oooooooooo' ,'oooo')
,('o o' ,'oooo oooa' ,'oo ooa')
,('er' ,'error' ,'eerorr', 'eerror')
,('a+b' ,'anna+bob' ,'aana++bbob')
) | % {
$message,$carrier,$expected = $_
$result = &$f $message $carrier
"$($result-in$expected): $result"
}
输出:
True: hhas iit arived?
True: hhas iit arived??
True: hass iit arrived?
True:
True: CCaats arre col.
True:
True: CCoouucchh
True: oooo
True: oo ooa
True: eerror
True: aana++bbob