139. Word Break

来源:互联网 发布:淘宝foreo旗舰店真假 编辑:程序博客网 时间:2024/06/04 19:24

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)]