Word Break

本文介绍了使用动态规划解决字符串分割问题的方法,通过构建布尔数组并遍历字符串,判断子串是否存在字典中来实现字符串的分割。示例代码演示了如何通过递归思考将问题分解为更小的部分,从而解决字符串分割任务。

摘要生成于 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".

 

动态规划的思想,分别考虑n+1个划分点是否是breakable的,当前i位置是否可以breakable由breakable[j]和s.substring(j,i)是否存在于dict中决定,即breakable[i]=

breakable[j]&dict.contains(s.substring(j,i)) 其中j∈[0,i-1].

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        int size = s.length();
        boolean[] breakable = new boolean[size+1];
        breakable[0] = true;
        for(int i=1;i<=size;i++) {
            for(int j=0;j<i;j++) {
                if(breakable[j]&&dict.contains(s.substring(j,i))) {
                    breakable[i] = true;
                    break;
                }
            }
        }
        return breakable[size];
    }
}

 

转载于:https://www.cnblogs.com/mrpod2g/p/4356981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值