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

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:

Input: s = “leetcode”, wordDict = [“leet”, “code”]
Output: true
Explanation: Return true because “leetcode” can be segmented as “leet code”.

给出一个字符串s,一个字典wordDict
问字符串s是否能分割成wordDict中的单词,字典中的单词可以重复使用,字典中不含重复单词

思路:
取每一段子串检查是否包含在字典中
每一段子串的方法:两个指针i, j,i = 0 ~ n(s的长度),j=0~i遍历substring(j , i)
字典可用HashSet

    public boolean wordBreak(String s, List<String> wordDict) {
        
        HashSet<String> hash = new HashSet<>(wordDict);
        int n = s.length();
        
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;
        
        for(int i = 1; i <= n; i++) {
            for(int j = 0; j < i; j++) {
                if(dp[j] && hash.contains(s.substring(j, i))) {
                    dp[i] = true;
                }
                //注意不能用下面这种错误的方法,因为一个i对应很多j,dp[i]即使更新为true,后面只要有一个j为false,就会把之前的true覆盖掉
                //dp[i] = dp[j] && hash.contains(s.substring(j, i)); //wrong
            }
        }
        
        return dp[n];
    }

也可以逐个判断substring是否和wordDict里面的单词相等,DFS

class Solution {
    Boolean[] dp;
    public boolean wordBreak(String s, List<String> wordDict) {
        dp = new Boolean[s.length()];
        return dfs(0, s, wordDict);
    }

    boolean dfs(int start, String s, List<String> wordDict) {
        if(start >= s.length()) return true;
        if(dp[start] != null) return dp[start]; //已经有结果,直接返回
        boolean res = false;

        for(String str : wordDict) {
            if(s.length() - start < str.length()) continue; //当前单词不够长度,换下一个
            if(s.substring(start, start+str.length()).equals(str) && dfs(start+str.length(), s, wordDict)) {
                res = true;
                break;
            }
        }
        dp[start] = res;
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值