LeetCode 139. Word Break C++

139. Word Break

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.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

Approach

  1. 题目大意就是wordDict中的字符串是否可以组成s,可以重复使用。虽然这道题是动态规划题,但自己还是忍不住暴力解,一开始构造字典树来解,可是题目要求的是整个字符串而不是序列,那么字典树就有点慢了,我又开始改造成unordered_set哈希表存字符串,速度明显提升,但是还是斗不过恶心的数据,所以还是要用动态规划来解,但是这里我用记忆化搜索会更通俗易懂,这里我把字符串的每个位置当做一个状态记录下来,从这个状态出发,看是否能匹配完成,然后记录下来,当下次又走到这个状态下,就可以直接返回,这些就是记忆化搜索的核心。

Code

class Solution {
public:
    int DFS(string &s, int n, int pos, unordered_set<string> &unst,vector<int> &cache) {
        if (pos == n)return 1;
        if (cache[pos] != 0)return cache[pos];
        for (int i = 1; i <=n-pos; i++) {
            string substr = s.substr(pos, i);
            if (unst.find(substr)!=unst.end()) {
                cache[pos]=DFS(s, n, pos + i, unst, cache);
                if (cache[pos] == 1)return 1;
            }
        }
        return -1;
    }
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string>unst;
        for (string &word : wordDict) {
            unst.insert(word);
        }
        vector<int>cache(s.size(), 0);
        return DFS(s, s.size(), 0, unst, cache)==1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值