Word Break

问题描述

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = “leetcode”,
dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.

思考: 如何找到最后解

想法:图算法,BFS和DFS,遍历到最后节点/用动态规划

  • 1、节点:(x)表示从0-X有word,即前缀长度
  • 2、边,表示从(x)到(y)可以加一个word到达;
  • 3、动态规划 dp[i] 表示0-i序列已经在字典找到,那么可以根据dp[i]更新dp[i + k],

代码

DFS

class Solution {
public:
    bool help(string &s, int now, unordered_set<string> &d, vector<bool> &visited){
        if(now >= s.length())
            return true;
        if(visited[now])
            return false;
        visited[now] = true;
        for(int i = now; i < s.length(); i++)
            if(d.find(s.substr(now, i - now + 1)) != d.end() && help(s,i + 1, d,visited))
                return true;
        return false;
    }
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<bool> visited(s.length(),false);
        return help(s,0,wordDict,visited);
    }
};

BFS

class Solution {
public:
    bool help(string &s,unordered_set<string> &d, vector<bool> &visited){
        if(s.length() == 0)
            return true;
        queue<int> q;
        visited[0] = true;
        for(q.push(0); !q.empty(); q.pop()){
            int ind = q.front();
            for(int i = ind; i < s.size(); i++)
                if(d.find(s.substr(ind, i - ind + 1)) != d.end()){
                    if(i + 1 >= s.length())
                        return true;
                   if(!visited[i + 1]){
                       q.push(i + 1);
                       visited[i + 1] = true;
                   }
                }
        }
    }
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<bool> visited(s.length(),false);
        return help(s,wordDict,visited);
    }
};

动态规划

class Solution {
public:
    bool help(string &s,unordered_set<string> &d, vector<bool> &dp){
        if(s.length() == 0)
            return true;
        dp[0] = true;
        for(int ind = 0; ind < s.size(); ind++){
            if(!dp[ind])
                continue;
            for(int i = ind; i < s.size(); i++)
                if(d.find(s.substr(ind, i - ind + 1)) != d.end()){
                    if(i + 1 >= s.length())
                        return true;
                   dp[i + 1] = true;
                }
        }
    }
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<bool> visited(s.length(),false);
        return help(s,wordDict,visited);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值