DP的递归关系?

时间:2011-04-06 18:13:16

标签: algorithm dynamic-programming text-segmentation

假设您有一个包含有效单词的词典。

给定一个删除了所有空格的输入字符串,确定字符串是否由有效单词组成。

您可以假设字典是提供O(1)查找的哈希表。

请为此提供重复关系。我在一本书中找到了这个问题,但这本书没有给出答案?

2 个答案:

答案 0 :(得分:2)

IsWordValid(S) = for word in dict:
                    if S.startsWith(word) and IsWordValid(S[word.length:])
                          return true
                 return false
IsWordValid(null) = true

答案 1 :(得分:0)

这是Mathematica中的代码,我开始为最近的代码高尔夫开发 它是一种最小匹配,非贪心,递归算法。这意味着句子“钢笔比剑更严厉”(没有空格)返回{“钢笔可能比剑还要厉害}:”

findAll[s_] :=
  Module[{a = s, b = "", c, sy = "="},
  While[
   StringLength[a] != 0,
   j = "";
   While[(c = findFirst[a]) == {} && StringLength[a] != 0,
    j = j <> StringTake[a, 1];
    sy = "~";
    a = StringDrop[a, 1];
   ];
   b = b <> " " <> j ;
   If[c != {},
    b = b <> " " <> c[[1]];
    a = StringDrop[a, StringLength[c[[1]]]];
   ];
  ];
   Return[{StringTrim[StringReplace[b, "  " -> " "]], sy}];
]

findFirst[s_] :=
  If[s != "" && (c = DictionaryLookup[s]) == {}, 
   findFirst[StringDrop[s, -1]], Return[c]];

示例输入

ss = {"twodreamstop", 
      "onebackstop", 
      "butterfingers", 
      "dependentrelationship", 
      "payperiodmatchcode", 
      "labordistributioncodedesc", 
      "benefitcalcrulecodedesc", 
      "psaddresstype", 
      "ageconrolnoticeperiod",
      "month05", 
      "as_benefits", 
      "fname"}

输出

 twodreamstop              = two dreams top
 onebackstop               = one backstop
 butterfingers             = butterfingers
 dependentrelationship     = dependent relationship
 payperiodmatchcode        = pay period match code
 labordistributioncodedesc ~ labor distribution coded es c
 benefitcalcrulecodedesc   ~ benefit c a lc rule coded es c
 psaddresstype             ~ p sad dress type
 ageconrolnoticeperiod     ~ age con rol notice period
 month05                   ~ month 05
 as_benefits               ~ as _ benefits
 fname                     ~ f name

HTH