鉴于:
找到单个单词的有效方法是什么?当用空格粘在一起时,这些单词组成了这个短语?
可能有多个解决方案,即使有些是胡言乱语:
理想情况下更喜欢PERL和/或正则表达式解决方案,但感谢任何建议。
答案 0 :(得分:1)
这个递归解决方案怎么样?
#!/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($@);
sub dictionary($);
# returns true if in dict
sub dictionary($) {
my ($str) = @_;
return(defined($wordsHash{$str}));
}
# recursive function
sub getParts($@) {
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)