Word Break

来源:互联网 发布:apache ab测试 linux 编辑:程序博客网 时间:2024/05/16 09:56

原题:

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>& wordDict) {        if(s.size() && wordDict.size()==0){            return false;        }        int len=s.size();        bool * dp=new bool[len+1];        for(int i=0; i<len+1; i++){            dp[i]=false;        }                int maxLen=0;        int minLen=(1<<31-1);        for(auto it=wordDict.begin(); it!=wordDict.end(); it++){            if(maxLen<it->size())                maxLen=it->size();            if(minLen>it->size())                minLen=it->size();        }                dp[0]=true;        for(int i=1; i<=len; i++){            for(int j=minLen; j<=i; j++){//j表示长度,从而一次计算[i-1,i),[i-2,i), [i-3,i)的字符串,看能否形成一个切分                if(wordDict.find(s.substr(i-j, j))!=wordDict.end())                    dp[i]=dp[i-j];//终点在i-1处可以到达                    if(dp[i])  break;            }        }        bool ret=dp[len];        delete [] dp;        return ret;    }};




0 0
原创粉丝点击