[LeetCode]Word Break

来源:互联网 发布:木工展开面积快速算法 编辑:程序博客网 时间:2024/06/06 15:40
解题思路:
动态规划问题,DP[i] 表示是否在wordDict中找到一种组合使得 s中 0到 i 的substr被 space-separated.
1,第一眼看到,就觉得一个for循环是不可能完成任务嗒,要两个for, 时间复杂度O(n2)
2,设置两个指针 i (0~len-1), j(i+1~len),每次去substr[ i ~ j ]
3,DP[ j -1 ] 设置为true的 前提是, i = 0(说明substr[0,j]可以在wordDict中直接找到)或者
     DP[i - 1] = true(这说明 i 之前的substr已经被找到,动态规划状态的转移就在这里)
4, 最后DP[ len - 1] 就是问题的答案

class Solution {public:    bool wordBreak(string s, unordered_set<string>& wordDict) {        int len = s.length();        vector<bool> DP(len, false);   // DP[i] means that is there a method to match word before s[i]        for (int i = 0; i < len; ++i){            for(int j = i+1; j < len+1; ++j){                string subs = s.substr(i, j-i);                if (wordDict.find(subs) != wordDict.end()){                    if ( i == 0 || DP[i-1]){                        DP[j-1] = true;                    }                }            }        }        return DP[len-1];    }};

0 0
原创粉丝点击