Problem link:

http://oj.leetcode.com/problems/word-break/

We solve this problem using Dynamic Programming method. Let A[0..n-1] be a boolean array, where A[i]=True if and only if s[i..n-1] can be segmented into words. The recursive formula is:

A[i] = True, if s[i..n-1] is a word

A[i] = True, if there exists j > i such that s[i..j-1] is a word and A[j] == True

A[i] = False, otherwise

We fill the A-table from i=n to 0, and return A[0] to tell if s[0..n-1] can be segmented into words.
(Note: there is another way that A[i] means if s[0..i] can be segmented, then the recursive formula becomes a little different, we fill the table from i=0 to n, and return A[n-1])

The pseudo-code is as follows

WORD-BREAK(string s, dictionary d):
let A[0..n-1] be a new array of False
for i = n-1 to 0
if A[i..n-1] is a word in d
A[i] = True
else
for j = i+1 to n-1
if A[j] == True and s[i..j-1] is a word in d
A[i] = True
break
return A[0]

And the following code is the python solution accepted by OJ.leetcode.

class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
"""
We solve this problem using DP
Define a boolean array A[0..n-1], where
A[i] = True, means s[i..n-1] can be segmented into words
------------------------------------
The recursive formula is:
A[i] = True, if there exists j>i (s[i..n-1] = s[i..j-1] + s[j..n-1])
such that s[i..j-1] is a word and A[j] = True
or A[i] = True, if A[i..n-1] is a word
------------------------------------
We fill A-table from i=n-1 to n
"""
n = len(s)
A = [False] * n
i = n-1
while i >= 0:
if s[i:n] in dict:
A[i] = True
else:
for j in xrange(i+1, n):
if A[j] and s[i:j] in dict:
A[i] = True
break
i -= 1
return A[0]

最新文章

  1. Mac OS sierra app is damaged
  2. C++ 编译报错
  3. java Map及Map.Entry详解
  4. CSS 魔法系列:纯 CSS 绘制图形(各种形状的钻石)
  5. node.js文件系统
  6. 2013 French Open Semifinal Press
  7. python(3)-计数器,有序字典
  8. LoadRunner调用Java程序—性能测试-转载
  9. oracle11 客户端安装及PLSQL和TOAD中文乱码
  10. RANSAC算法详解
  11. Java 过滤器的作用
  12. 五子棋的判断输赢规则 -- java编程(简单优化完整版)
  13. 从koa-session源码解读session本质
  14. React Native搭建开发环境 之 --走过的坑
  15. delphi idhttp post 普通提交乱码处理
  16. P4248 [AHOI2013]差异
  17. odoo开发笔记--模型字段compute用法
  18. Error:The supplied javaHome seems to be invalid. I cannot find the java executable. Tried location:
  19. C语言 string::size_type类型
  20. 自己实现一个双向绑定的Vue

热门文章

  1. HTML5自学笔记[ 5 ]JSON的新方法
  2. 笔记3:关于VBS整人代码的浅谈
  3. python与unicode
  4. js打印图形
  5. 初学java之JFrame窗口模式
  6. 简述 Ruby 与 DSL 在 iOS 开发中的运用
  7. MySql与SqlServer的一些常用用法的差别
  8. GPOR
  9. Objective-C:Category
  10. C#重启系统代码