📜  断字问题| DP-32 |套装– 2

📅  最后修改于: 2021-04-24 20:34:46             🧑  作者: Mango

给定一个非空序列S和一个包含非空单词列表的字典dict [] ,请打印所有可能的方法以将各个字典单词中的句子打断。
例子:

本文讨论了与此类似的问题,其中的任务是检查是否存在任何解决方案,以便可以将序列分解为词典单词。
方法:想法是检查从任何位置I开始的每个子字符串,使其结束于字典中存在的字符串的长度,然后简单地递归子字符串[0,I]。同时,为每个子字符串存储重叠的子问题,以避免再次计算子问题。重叠的子问题可以如下所示–

下面是上述方法的实现:

C++
// C++ implementation to break
// a sequence into the words of
// the dictionary
 
#include 
 
using namespace std;
 
// Unordered_map used for storing
// the sentences the key string
// can be broken into
unordered_map > mp;
 
// Unordered_set used
// to store the dictionary.
unordered_set dict;
 
// Utility funtion used for
// printing the obtained result
void printResult(vector A)
{
    for (int i = 0; i < A.size(); i++)
        cout << A[i] << '\n';
}
 
// Utility function for
// appending new words
// to already existing strings
vector combine(
     vector prev, string word){
     
    // Loop to find the append string
    // which can be broken into
    for (int i = 0; i < prev.size(); i++) {
        prev[i] += " " + word;
    }
    return prev;
}
 
// Utility funtion for word Break
vector wordBreakUtil(string s)
{  
    // Condition to check if the
    // subproblem is already computed
    if (mp.find(s) != mp.end())
        return mp[s];
    vector res;
     
    // If the whole word is a dictionary
    // word then directly append into
    // the result array for the string
    if (dict.find(s) != dict.end())
        res.push_back(s);
     
    // Loop to iterate over the substring
    for (int i = 1; i < s.length(); i++) {
        string word = s.substr(i);
         
        // If the substring is present into
        // the dictionary then recurse for
        // other substring of the string
        if (dict.find(word) != dict.end()) {
            string rem = s.substr(0, i);
            vector prev =
             combine(wordBreakUtil(rem), word);
            res.insert(res.end(),
                 prev.begin(), prev.end());
        }
    }
     
    // Store the subproblem
    // into the map
    mp[s] = res;
    return res;
}
 
// Master wordBreak function converts
// the string vector to unordered_set
vector wordBreak(string s,
             vector& wordDict)
{
    // Clear the previous stored data
    mp.clear();
    dict.clear();
    dict.insert(wordDict.begin(), wordDict.end());
    return wordBreakUtil(s);
}
 
// Driver Code
int main()
{
    vector wordDict1 = {
        "cat", "cats", "and", "sand", "dog" };
    printResult(wordBreak("catsanddog", wordDict1));
    return 0;
}


Python3
# Python3 implementation to break
# a sequence into the words of
# the dictionary
  
# Unordered_map used for storing
# the sentences the key string
# can be broken into
mp = dict()
  
# Unordered_set used
# to store the dictionary.
dict_t = set()
  
# Utility funtion used for
# printing the obtained result
def printResult(A):
 
    for i in range(len(A)):
        print(A[i])
  
# Utility function for
# appending new words
# to already existing strings
def combine( prev, word):
      
    # Loop to find the append string
    # which can be broken into
    for i in range(len(prev)):
     
        prev[i] += " " + word;
     
    return prev;
 
# Utility funtion for word Break
def wordBreakUtil(s):
 
    # Condition to check if the
    # subproblem is already computed
    if (s in mp):
        return mp[s];
     
    res = []
      
    # If the whole word is a dictionary
    # word then directly append into
    # the result array for the string
    if (s in dict_t):
        res.append(s);
      
    # Loop to iterate over the substring
    for i in range(1, len(s)):
         
        word = s[i:];
          
        # If the substring is present into
        # the dictionary then recurse for
        # other substring of the string
        if (word in dict_t):
             
            rem = s[:i]
            prev = combine(wordBreakUtil(rem), word);
            for i in prev:
                res.append(i)
      
    # Store the subproblem
    # into the map
    mp[s] = res;
    return res;
  
# Master wordBreak function converts
# the string vector to unordered_set
def wordBreak(s,  wordDict):
 
    # Clear the previous stored data
    mp.clear();
    dict_t.clear();
    for i in wordDict:
        dict_t.add(i)
    return wordBreakUtil(s);
 
# Driver Code
if __name__=='__main__':
 
    wordDict1 = ["cat", "cats", "and", "sand", "dog" ]
    printResult(wordBreak("catsanddog", wordDict1));
 
# This code is contributed by rutvik_56


输出:
cat sand dog
cats and dog