Leetcode: Word Break
2015-08-29 12:57
309 查看
Question
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”.
Show Tags
Show Similar Problems
Solution
Analysis
Get idea from Code Ganker”s CSDNif using recursive function, the one substring will be calculated many times. That’s why we use dynamic programming. flag[i] records whether substring[0:i+i] is satisfied.
Code
[code]class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ if s=='': return True flag = [False]*(len(s)+1) flag[0] = True for ind in range(len(s)): newstr = s[:ind+1] for inind in range(len(newstr)): if flag[inind] and newstr[inind:] in wordDict: flag[ind+1] = True break return flag[len(s)]
相关文章推荐
- div块级元素内文字换行word-wrap, word-break,white-space。
- HTTP协议
- BZOJ1189: [HNOI2007]紧急疏散evacuate 二分+最大流
- log4j日志配置
- ffmpeg超详细综合教程——摄像头直播
- try catch finally中含有return时的处理步骤
- 总线设备驱动模型
- Aircrack-ng之Airmon-ng命令
- NS2网络仿真环境的搭建和使用
- viewpager setpagechangelistener解释与应用到如微信的页面转换的渐变效果
- grep、egrep、正则表达式
- Delete Node in a Linked List 单链表删除节点
- [刷题]Permutations II
- hdu 5406 CRB and Apple 求两个不相交的不下降子序列之和最大
- c++静态库与动态库的区别
- 数据源的配置
- 惠普学习感想
- Java 多线程
- java语句与流程控制
- hdu 4368 树状数组 离线维护