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. You may assume the dictionary does not contain duplicate words.

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

Return true because "leetcode" can be segmented as "leet code".

UPDATE (2017/1/4):

The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.



我的解法是DFS,但在Discuss中还有dp的解法,一开始用的递归但是没写出来,后面想了很久还是用while+队列的形式解的

此题的DFS思路就是  先用start 与 end进行切割,如找到了leet,则在leet的基础上令start=end+1,end继续往后面循环,直到end超过string.size()-1

小细节是需要用增加一个记录start的无序表,避免超时

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        if(wordDict.size()==0||s.size()==0)
            return false;
        unordered_set<int> visited;    //一开始没这个东西,但是超时了
        queue<int> q;
        q.push(0);
        while(!q.empty()){
            int start=q.front();
            q.pop();
            if(visited.find(start)==visited.end()){
                visited.insert(start);
                for(int end=start;end<s.size();end++){
                    string temp=s.substr(start,end-start+1);
                    if(find(wordDict.begin(),wordDict.end(),temp)!=wordDict.end()){
                        q.push(end+1);
                        if(end+1==s.size())
                            return true;
                    }
                }
            }
        }
        return false;
    }
};


DP版本的:

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


python版本:

class Solution:
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        dp=[False]*(len(s)+1)
        dp[0]=True
        for i in range(1,len(s)+1):
            for j in range(i):
                if dp[j] and s[j:i] in wordDict:
                    dp[i]=True
        return dp[len(s)]


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值