2014-03-03 43 views
-1

鑑於分裂的字母爲有效的字的字符串:填字:從字典

  1. 與空間移出並轉換爲小寫的短語 - 例如「胳膊上的一槍」中的「ashotinthearm」;
  2. 字典返回true,或者如果一個字存在虛假( 「A」, 「因爲」, 「灰」, 「拍」, 「熱」,等等,都會返回true)

什麼是一種有效的方法來查找單詞,當與空間粘在一起時,就構成了這個詞組?

可以有多於一個的解決方案,即使有些是亂碼:

  • ashotinthearm(在一針強心劑,在臂作爲熱)
  • asintended(如預期,如在往往)
  • brothersinlaw
  • guysanddolls(紅男綠女,沙人玩偶)
  • haveascrewloose(法律,哥哥罪依法兄弟)(有螺絲鬆動,有船員鬆)
  • ifeelthepinch(我感到了壓力,如果鰻魚捏)
  • isinyourcourt(是你的了,我的罪你的法院)
  • 公館也許(莊園,人或房屋)
  • manormouse(人或鼠標,莊園鼠標)
  • 新西蘭(紐西蘭,新的熱情和)
  • oneatatime(一次一個,在吃飯時間)
  • portableradio(便攜式收音機,端口能夠收音機)
  • scotspine(歐洲赤松, scot spine)
  • shopsoiled(店弄髒,塗油店)

會非常喜歡PERL和/或正則表達式的解決方案,但感激的任何建議。

+0

這將是很難做到的。在哪裏放置正則表達式的重點.. – sln

+0

是不是有一個像這樣的linux命令?它從句子或單詞中找到anagrams,它們是相似的。 – TLP

回答

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([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) 
+1

不要使用[原型](http://perldoc.perl.org/perlsub.html#Prototypes),除非您知道它們的用途。這是模仿一些Perl內置函數的非標準行爲。 – TLP

+0

非常感謝RobbySherwood提供的優雅解決方案。關鍵的見解是使用遞歸。 給出的代碼完美無缺。 TLP正確地指出了原型的一些古怪之處;也許RobbySherwood來自C背景? 一些簡單的變化 - 僅僅是挑剔的 - 使它更加「完美」可能包括 'if(length($ phrase)== 0) - > if(!$短語) for(my $ i = 1; $ i <= length($ phrase); $ i ++) - > for my $ i(1 .. length($ phrase)) 最後的「return」 getParts是不需要的' (我無法解決如何在單獨的行上顯示上述內容...) – mikeham

+0

YES! C背景... :-) – RobbySherwood