139. Word Break

本文介绍了一种判断字符串是否能被拆分为字典中单词序列的方法,包括深度优先搜索(DFS)和动态规划(DP)两种实现方式。DFS通过记忆化搜索减少重复计算,而DP则通过构建布尔数组来记录子串的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


还是dfs搜,从前往后看看有没有在字典里出现过的,有就切,并且递归往下传。

必须要记忆优化,否则太多重复判断直接TLE

 HashMap<String, Boolean> hashMap=new HashMap<>(1024);
	
	public boolean wordBreak(String s, Set<String> wordDict)
	{
		return dfs(s, wordDict);
	}


	private boolean dfs(String s, Set<String> dict)
	{

		int len = s.length();
		if (len == 0)
			return true;
		
		if(hashMap.containsKey(s))
			return hashMap.get(s);
		
		for (int i = 1; i <= len; i++)
		{
			String substr = s.substring(0, i);
			if (dict.contains(substr))
				if (dfs(s.substring(i), dict))
					{
						hashMap.put(s, true);
						return true;
					}
		}
		
		hashMap.put(s, false);
		return false;
	}


-----------------------------------------------------------------------------------------------------------

另外比较好的方法dp,摘自:https://leetcode.com/discuss/18904/java-implementation-using-dp-in-two-ways

f[i] stands for whether subarray(0, i) can be segmented into words from the dictionary. So f[0] means whether subarray(0, 0) (which is an empty string) can be segmented, and of course the answer is yes.

The default value for boolean array is false. Therefore we need to set f[0] to be true.


public boolean wordBreak(String s, Set<String> dict) {

        boolean[] f = new boolean[s.length() + 1];

        f[0] = true;
        for(int i=1; i <= s.length(); i++){
            for(int j=0; j < i; j++){
                if(f[j] && dict.contains(s.substring(j, i))){
                    f[i] = true;
                    break;
                }
            }
        }

        return f[s.length()];
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值