码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Word Break

时间:2014-11-23 17:13:25      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   java   for   on   

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 }

 

Leetcode Word Break

标签:style   blog   io   ar   color   sp   java   for   on   

原文地址:http://www.cnblogs.com/criseRabbit/p/4116672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!