word-break

来源:互联网 发布:佰斯纳特 淘宝 编辑:程序博客网 时间:2024/05/17 09:32

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

这道题目可以利用动态规划的方法来做,首先设置dp[i]为以i结尾的是否能被字典分割. dp[i]和dp[j]和i-j之间的字符是否在字典中有关.

class Solution {public:    bool wordBreak(string s, unordered_set<string> &dict) {    const unsigned int len = s.size();    if (len == 0)        return false;    char* dp = new char[len];  //保存字符0-i之间是否能被字典分割.    memset(dp, 0, sizeof(*dp)*len);    int maxsize = 0;    for (auto iter = dict.cbegin(); iter != dict.end(); ++iter)//计算字典中的最长字符串可以减少判断的次数    {        if (iter->size() > maxsize)            maxsize = iter->size();    }    if (dict.find(s.substr(0, 1)) != dict.end())   //设置dp[0]    {        dp[0] = 1;    }    for (int i = 1; i != len; ++i)    {        if (i+1<= maxsize&&dict.find(s.substr(0, i + 1)) != dict.cend()) //判断是否从0-i在字典中,当然长度要小于字典中的最大长度.        {               dp[i] = 1;            continue;        }        for (int j = i - 1; j >= 0 && (i - j) <= maxsize; --j) //判断dp[j]为真和i-j在字典中是否同时成立        {            if (dp[j] == 1 && dict.find(s.substr(j+1, i - j)) != dict.cend()){                dp[i] = 1;                break;            }        }    }    bool res=dp[len-1];    delete[] dp;  //释放空间    return res;         }};
0 0
原创粉丝点击