leetcode--Word Break

Given a string s and a dictionary of words dict, determine ifs 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".


题意:给定一个字符串s,和字典,判断s能否由字典内的一个或者多个单词组合而成。

分类:动态规划


解法1:动态规划。使用flag[i]来表示从0到i构成的子串能否用字典来表示,那么我们要求的就是flag[s.length()]

对于flag[i],它由flag[j]和s.substring(j,i)这个子串决定,如果i之前存在一个j,使flag[j]为true,那么我们只要判断j到i这部分子串,是否在字典里面

如果在,那么显然flag[i]也为true

[java]  view plain  copy
  1. public class Solution {  
  2.     public boolean wordBreak(String s, Set<String> wordDict) {  
  3.         if(s.length()==0return true;  
  4.         if(wordDict.isEmpty()) return false;  
  5.         boolean flag[] = new boolean[s.length()+1];  
  6.         flag[0] = true;  
  7.         for(int i=1;i<=s.length();i++){  
  8.             for(int j=i-1;j>=0;j--){  
  9.                 if(flag[j]&&wordDict.contains(s.substring(j,i))){//判断子串  
  10.                     flag[i] = true;  
  11.                     break;  
  12.                 }  
  13.             }  
  14.         }  
  15.         return flag[s.length()];  
  16.     }  
  17. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46563687

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值