139. Word Break 单词切分

来源:互联网 发布:淘宝网迷你小音响 编辑:程序博客网 时间:2024/05/19 14:15

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

1. 与之前答案相同,不要问我怎么做,因为我也是背下来的。。。

class Solution {public:bool wordBreak(string s, unordered_set<string>& wordDict) {    int n = s.size();    vector<bool> label(n+1, false);    label[0] = true;    for(int i = 1; i <= n; i++){        for(int j = 1; j <= i; j++){            if(label[i-j] == true){                string str = s.substr(i-j,j);                if(wordDict.find(str) != wordDict.end())                    label[i] = true;            }        }    }    return label[n];}};


2.别人的答案 这个比较好理解

bool wordBreak(string s, unordered_set<string> &dict) {        if(dict.size()==0) return false;                vector<bool> dp(s.size()+1,false);        dp[0]=true;                for(int i=1;i<=s.size();i++)        {            for(int j=i-1;j>=0;j--)            {                if(dp[j])                {                    string word = s.substr(j,i-j);                    if(dict.find(word)!= dict.end())                    {                        dp[i]=true;                        break; //next i                    }                }            }        }                return dp[s.size()];    }


0 0
原创粉丝点击