Word Break

来源:互联网 发布:mac电脑excel内存不足 编辑:程序博客网 时间:2024/05/24 05:01

题目描述:

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

思路:本题的重点在于两个for循环里面的第一个if判断里的动态规划递推式。

public class Word_Break {public static boolean wordBreak(String s, List<String> dict) {//result[i]表示在i之前(不包括i)能否用字典里的字符串表示sboolean result[]=new boolean[s.length()+1];result[0] = true;for(int i=0;i<=s.length();i++){for(int j=0;j<i;j++){String str = s.substring(j, i);//这个判断的意思是j之前(不包括j)都可以用字典里的字符表示,并且j到i(不包括i)这段字符在字典里//那么符合这两点也就意味着在i之前(不包括i)能用字典里的字符串表示if(result[j]&&dict.contains(str)){result[i]=true;}if(result[i]){break;}}}return result[s.length()];}public static void main(String[] args) { String s = "leetcode"; ArrayList<String> dict =new  ArrayList<String>(); dict.add("leet"); dict.add("code"); System.out.println(wordBreak(s,dict));}}


原创粉丝点击