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

对于这道题,最终结果是由子问题决定的,而上一步的问题是由下一步来决定,因此可以考虑用动态规划的思想来解决。

首先需要建立一张表,用来保存当前子问题的状态,这里我们用hashmap来存储

Map<Integer,Boolean> map=new HashMap<Integer,Boolean>();

key用来存储从上一个分割点为止到这个分割点的词是存在于字典中的。如果是,我们就把值设置为true。

最后检验len的值是否为true,如果为是则说明该字符串可切分。

 1 package Word.Break;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 import java.util.Map.Entry;
 8 import java.util.Set;
 9 
10 public class WordBreak {
11 public boolean wordBreak(String s, Set<String> dict) {
12      int len=s.length();
13     Map<Integer,Boolean> map=new HashMap<Integer,Boolean>();
14     map.put(0, true);
15     for(int i=1;i<len+1;i++){
16         map.put(i, false);
17     }
18     for(int i=0;i<len;i++){
19         if(map.get(i)){
20             for(int j=i;j<len+1;j++){
21                 String sub=s.substring(i, j);
22                 if(dict.contains(sub)){
23                     map.remove(j);
24                     map.put(j, true);
25                 }
26             }
27         }
28     }
29     boolean result=map.get(len);
30     return result;
31     
32     }
33 
34 }

 

转载于:https://www.cnblogs.com/criseRabbit/p/4116672.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值