Week12

问题描述

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

思路

这道题的意思是,给我们一个字符串和一个储存有多个单词的 vector,问我们是否能够通过在字符串中加入空格来实现把字符串分割成多个 vector 中的单词。这道题属于动态规划的题目,所以我一开始就想像之前做其他动态规划问题一样找初始状态,状态转移方程,想要使用递推来从小问题推到大问题来解决问题,但是发现这道题用这种思路好像不是很清晰,所以用了一个更加容易理解更加清晰的思路——一个字符串如果是可以分成 vector 中的单词的话,那么字符串结尾的部分(右半部分)一定有一个单词。然后我们检查左半部分是否可以拆分成单词,而这其实和上一步一样,也是检查左半部分子串中的右半部分(结尾部分)是否有单词以及左半部分是否还是可分。例如applepenapple -> {applepen, apple},左半部分 applepen -> {apple, pen}。如果最后发现每一部分都是可以分成单词的,那么这个字符串就是可分的,返回 true,若其中一部分不可分,这个字符串就不可分,返回 false。这其实就是递归。但是,我们可以在递归的时候对一些中间结果做一下存储,一些子串的可分不可分情况可以储存在一个map里面,下一次遇到相同的子串就不用重复递归了。这是记忆化递归,也是动态规划的一种。
在这里插入图片描述

代码

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        map<string, int> dict;
        for(auto c : wordDict){
            dict[c] = 1;
        }
        
        return recurCheck(s, dict);
    }
    
    bool recurCheck(string s, map<string, int> dict){
        // 使用memory_can_break.count() 以及 dict.count()来判断字串是否在map里面
        // 如果之前已经储存有该字串可分不可分的情况了,直接返回
        if(memory_can_break.count(s)) return memory_can_break[s];
        // 如果该字串就是一个单词,返回true,并且记录可分情况在memory_can_break里面
        if(dict.count(s)){ // 使用dict.count()来判断字串是否在map里面
            memory_can_break[s] = true;
            return true;
        }
        // 开始分割
        for(int i = 0; i < s.length(); i++){
            string left = s.substr(0, i);
            string right = s.substr(i);
            if(dict.count(right) && recurCheck(left, dict)){
                memory_can_break[s] = true;
                return true;
            }
        }
        memory_can_break[s] = false;
        return false;
    }
private:
    unordered_map<string, bool> memory_can_break;
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值