LeetCode 139. Word Break (Medium)

来源:互联网 发布:快乐大本营知乎 编辑:程序博客网 时间:2024/05/26 02:21

题目描述:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

Example:

s = "leetcode",dict = ["leet", "code"].Return true because "leetcode" can be segmented as "leet code".

题目大意:给出一个字符串,给出一个字符串数组(字典),问字符串是否能分解为字典里的字符串。

思路:暴力做法当然是遍历所有子字符串组合,显然时间复杂度太高。从网上看到可以动态规划,学习了一下。大概思路是:假如前i个字符可以切分(由字典的字符串组成),那看看前i - j个字符能否被切分,如果可以就继续。复杂度貌似是O(n^2)。
c++代码:

class Solution {public:    bool wordBreak(string s, vector<string>& wordDict) {        vector<bool> dp(s.size() + 1, false);        dp[0] = true;        for (int i = 1; i < s.size() + 1; i++)        {            for (int j = i - 1; j >= 0; j--)            {                if (dp[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i - j)) != wordDict.end())                {                    dp[i] = true;                    break;                }            }        }        return dp[s.size()];    }};
原创粉丝点击