139. Word Break

题目描述

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given s ="leetcode",dict =["leet", "code"].Return true because"leetcode"can be segmented as"leet code".

思路

这个问题一个常见的思路就是递归,枚举一个地方划分的所有可能,然后对剩余的子串递归,只要有一个枚举是成功的,break,递归函数返true,
进一步优化时间效率,我们可以把这个递归版本翻译成动态规划版本,保存中间的信息,相当于保存了一些中间的子串递归函数的结果,不用
再去调用

代码实现1

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
    	
        if(dict.find(s)!=dict.end())
        	return true;
        int n=s.length();
        //由于递推时,需要用到长度为0的情况
        //所以,为了地递推的方便,这里dp的下标表示长度
        vector<bool> dp(n+1,false);
        //要合理的初始化使之满足递推公式的要求
        dp[0] = true;
        for(int i=1;i<=n;i++)
         {
            for(int j=0;j<i;j++)
            {
                if(dp[j] && dict.find(s.substr(j,i-j))!=dict.end())
                {
                  dp[i] = true;
                  break;
                }
            }
        }
        return dp[n];
    }
};

代码实现2

对上面代码的优化:字典中的单词的长度是有限度的,不必穷举所有的长度

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        
        if(dict.find(s)!=dict.end())
            return true;
        int n=s.length();
        vector<bool> dp(n+1,false);
        dp[0] = true;//要合理的初始化使之满足递推公式的要求
        int minLen = n;
        int maxLen = 0;
        for(auto word:dict)
        {
            int temp = word.length();
            minLen = min(minLen,temp);
            maxLen = max(maxLen,temp);
        }
        for(int i=1;i<=n;i++)
         {
            for(int l=minLen;l<=maxLen && l<=i;l++)
            {
                if(dict.find(s.substr(i-l,l))!=dict.end() && dp[i-l])
                {
                  dp[i] = true;
                  break;
                }
            }
        }
        return dp[n];
    }
};

posted on 2021-05-02 22:01  朴素贝叶斯  阅读(29)  评论(0编辑  收藏  举报

导航