word-break

原文地址:https://www.jianshu.com/p/8a11fe8ba14b

时间限制:1秒 空间限制:32768K

题目描述

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".

我的代码

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        int siz=s.size();
        if(dict.find(s)!=dict.end())
            return true;
        for(int i=1;i<siz;i++){
            string word=s.substr(i);
            if(dict.find(word)==dict.end())
                continue;
            if(wordBreak(s.substr(0,i),dict))
                return true;
        }
        return false;
    }
};

运行时间:5ms
占用内存:704k

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        int siz=s.size();
        vector<bool> dp(siz+1,false);
        dp[0]=true;//记录s.substr(0,i)是否可以分词
        for(int i=1;i<=siz;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[siz];
    }
};

运行时间:6ms
占用内存:608k

原文地址:https://www.cnblogs.com/cherrychenlee/p/10844118.html