word-break
题目描述:
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".
输出描述:
首先要理解题意,给一个字符串判断其能否分成字典中的单词,如果能分成则返回true。
知识点:
动态规划
解题思路:
【个人思路】
首先想到的是从头开始遍历字符串,然后取出子字符串和dict进行比较,看是否包含该单词。但是需要注意的是当取出的字符串中的子字符串进行比较之后需要记录下分割之后的点。这就是动态规划的思想,就是利用之前记录或是计算过的,然后继续进行计算。所以一边要记录在哪里进行过分割,一边要比较字符串是否相等。利用外循环来递增长度,用内循环寻找分割点。
具体代码:
package Tencent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo_2 {
public static void main(String[] args){
String s="leetcode";
Set<String> dict=new HashSet<String>();
dict.add("leet");
dict.add("code");
dict.add("fish");
boolean result=wordBreak(s,dict);
System.out.print(result);
}
private static boolean wordBreak(String s, Set<String> dict) {
// TODO Auto-generated method stub
int len=s.length();
boolean[] dp=new boolean[len+1];
Arrays.fill(dp, false);
dp[0]=true;
for(int i=1;i<=len;++i){
for(int j=0;j<i;++j ){
if(dp[j]&&dict.contains(s.substring(j,i))){
dp[i]=true;
break;
}
}
}
return dp[len];
}
}
注意点:
思路很巧妙,就是将已经判定是单词的地方进行标记。然后最后和字符长度一致的标记分割点的数组的最后一个元素要是为true的话,则字符串可以分割成字典中的单词。
本文探讨了LeetCode上的word-break问题,分析如何使用动态规划策略判断字符串是否能分解为字典中的单词。通过遍历字符串并记录分割点,如果最后分割点数组的最后一个元素为true,则表明字符串可分割。

1万+

被折叠的 条评论
为什么被折叠?



