Word Break(medium)

【题目】

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".

【题意】

      给定词典的情况下,看看原字符串能不能全部成功地被给定的词典分割。

【分析】

     最自然的想法是,使用递归。提交,超时了。想想,这个问题其实具有动态规划的特点。比如计算catsanddog的分割方式,那么倒着想如下:
到了最后一个字符g的时候,
如果能在g之前切一刀,也就是说,如果g在词典中以及catsanddo能够成功切分,那么原字符串就可以成功切分。
或者,如果能在og之前切一刀,也就是说,如果og在词典中以及catsandd能够成功切分,那么原字符串就可以成功切分。
或者,如果能在dog之前切一刀,也就是说,如果dog在词典中以及catsand能够成功切分,那么原字符串就可以成功切分。
或者,如果能在ddog之前切一刀,也就是说,如果ddog在词典中以及catsan能够成功切分,那么原字符串就可以成功切分。
或者,如果能在nddog之前切一刀,也就是说,如果nddog在词典中以及catsa能够成功切分,那么原字符串就可以成功切分。
或者,如果能在anddog之前切一刀,也就是说,如果anddog在词典中以及cats能够成功切分,那么原字符串就可以成功切分。
或者,如果能在sanddog之前切一刀,也就是说,如果sanddog在词典中以及cat能够成功切分,那么原字符串就可以成功切分。
或者,如果能在tsanddog之前切一刀,也就是说,如果tsanddog在词典中以及ca能够成功切分,那么原字符串就可以成功切分。
或者,如果能在atsanddog之前切一刀,也就是说,如果atsanddog在词典中以及c能够成功切分,那么原字符串就可以成功切分。
或者,如果能在catsanddog之前切一刀,也就是说,如果catsanddog在词典中以及""能够成功切分,那么原字符串就可以成功切分。
使用一个数组bool wordB[i] 来记录,在单词长度为i的时候,能否成功切分(i取值范围必然为[ 0, word.length() ] )

【实现】

public class Solution {
    static int dp[];
		static String string;
	 public static boolean wordBreak(String s, Set<String> dict) {
		 if(s==null || s.length()==0) return false;
        dp = new int[s.length()+1];
        string = s;
        return find(0, dict);
	  }
	 public static boolean find(int s, Set<String> set){
		  if(dp[s] == -1) return false;
        if( s == string.length() || dp[s] == 1) return true;
        // System.out.println(s);
        String tmpstr = string.substring(s,string.length());
        //System.out.println(tmpstr);
        boolean find = false;
        for(String str:set){
            if(tmpstr.startsWith(str)){
                find =  find(s+str.length(), set);
            }
            if(find){
                dp[s] = 1;
                return true;
            }
        }
        dp[s] = -1;
        return false;
	 }
}

// LeetCode, Word Break
// 深搜,超时
// 时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        return dfs(s, dict, 0, 0);
    }
private:
    static bool dfs(const string &s, unordered_set<string> &dict,
            size_t start, size_t cur) {
        if (cur == s.size()) {
            return dict.find(s.substr(start, cur-start+1)) != dict.end();
        }
        if (dfs(s, dict, start, cur+1)) return true;
        if (dict.find(s.substr(start, cur-start+1)) != dict.end())
            if (dfs(s, dict, cur+1, cur+1)) return true;
        return false;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值