码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Word Break"

时间:2014-08-08 08:27:25      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   art   ar   

My first solution was DFS - TLE. Apparently, DFS with TLE usually means DP. 

1D DP + Rolling Array:

class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        int len = s.length();
        int lend= dict.size();
        if(len == 0 || lend == 0) return false;
        
        //    Init
        vector<bool> rec0, rec1;
        rec0.resize(len); rec1.resize(len);
        std::fill(rec0.begin(), rec0.end(), false);
        std::fill(rec1.begin(), rec1.end(), false);

        //
        vector<bool> &pre = rec0;
        vector<bool> &post = rec1;

        //    Start from 0
        for(int i = 1; i <= len; i ++)
        {
            string sub = s.substr(0, i);
            if(dict.find(sub) != dict.end())
            {
                pre[i-1] = true;
                if(i == len) return true;
            }
        }

        for(int i = 1; i < len; i ++)    // vertical
        {
            for(int j = 0; j < len; j ++)    // horizontal
            {
                if(pre[j])
                {
                    for(int k = 1; k < len - j; k ++)
                    {
                        string sub = s.substr(j + 1, k);
                        if(dict.find(sub) != dict.end())
                        {
                            post[j + k] = true;
                            if((j + k + 1) == len) return true;
                        }
                    }
                }
            }
            //    Rolling array
            if(i % 2)
            {
                pre = rec1; post = rec0;
            }
            else
            {
                pre = rec0; post = rec1;
            }
        }

        return false;
    }
};

LeetCode "Word Break",布布扣,bubuko.com

LeetCode "Word Break"

标签:style   blog   color   os   io   for   art   ar   

原文地址:http://www.cnblogs.com/tonix/p/3898523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!