139. 单词拆分
原文链接:https://blog.csdn.net/qq_39355828/article/details/120615212 (opens new window)
- 单词拆分
给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入: s = “leetcode”, wordDict = [“leet”, “code”]
输出: true
解释: 返回 true 因为 “leetcode” 可以被拆分成 “leet code”。
动态规划:维护布尔性数组dp[n+1],dp[i]=true,表示s(0)到s(i)可以由单词表中的元素组成。转移方程为: dp[i]=dp[j]&&wo.contains(s.substring(j,i))
class Solution {
public boolean wordBreak(String s, List<String> wordDict)
{
boolean[] dp=new boolean[s.length()+1];
Set<String>wo=new HashSet<>(wordDict);
dp[0]=true;
for(int i=1;i<=s.length();i++)
{
for(int j=0;j<i;j++)
{
if(dp[j]&&wo.contains(s.substring(j,i)))
{dp[i]=true;
break;}
}
}
return dp[s.length()];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编辑 (opens new window)
上次更新: 2026/08/11, 13:36:18