這個遞歸解決方案呢?
#!/usr/bin/perl -wW
use strict;
#global "constants"
my @words=("a", "as", "ash", "shot", "hot", "in", "the", "arm");
my %wordsHash = map { $_ => 1 } @words;
sub getParts([email protected]);
sub dictionary($);
# returns true if in dict
sub dictionary($) {
my ($str) = @_;
return(defined($wordsHash{$str}));
}
# recursive function
sub getParts([email protected]) {
my ($phrase, @priorWords) = @_ ;
print "DEBUG: step prior words(" . join(" ", @priorWords) . ") phrase($phrase) \n";
#recursion end:
if(!$phrase) {
print "solution:" . join(" ", @priorWords) . "\n";
return;
}
for my $i (1 .. length($phrase)) {
my $word = substr($phrase,0,$i);
if(dictionary($word)) {
getParts(substr($phrase,$i),(@priorWords,$word));
}
}
}
getParts("ashotinthearm",());
輸出是:
DEBUG: step prior words() phrase(ashotinthearm)
DEBUG: step prior words(a) phrase(shotinthearm)
DEBUG: step prior words(a shot) phrase(inthearm)
DEBUG: step prior words(a shot in) phrase(thearm)
DEBUG: step prior words(a shot in the) phrase(arm)
DEBUG: step prior words(a shot in the a) phrase(rm)
DEBUG: step prior words(a shot in the arm) phrase()
solution:a shot in the arm
DEBUG: step prior words(as) phrase(hotinthearm)
DEBUG: step prior words(as hot) phrase(inthearm)
DEBUG: step prior words(as hot in) phrase(thearm)
DEBUG: step prior words(as hot in the) phrase(arm)
DEBUG: step prior words(as hot in the a) phrase(rm)
DEBUG: step prior words(as hot in the arm) phrase()
solution:as hot in the arm
DEBUG: step prior words(ash) phrase(otinthearm)
這將是很難做到的。在哪裏放置正則表達式的重點.. – sln
是不是有一個像這樣的linux命令?它從句子或單詞中找到anagrams,它們是相似的。 – TLP