博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode]Word Break @ Python
阅读量:7217 次
发布时间:2019-06-29

本文共 810 字,大约阅读时间需要 2 分钟。

原题地址:https://oj.leetcode.com/problems/word-break/

题意:

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

解题思路:这道题考察的显然不是dfs,为什么?因为这道题不需要给出如何分割的答案,只需要判断是否可以分割为字典中的单词即可。我们考虑使用动态规划,这个思路看代码的话不难,用python写起来也比较清晰。

代码:

class Solution:    # @param s, a string    # @param dict, a set of string    # @return a boolean    # @good coding!    def wordBreak(self, s, dict):        dp = [False for i in range(len(s)+1)]        dp[0] = True        for i in range(1, len(s)+1):            for k in range(i):                if dp[k] and s[k:i] in dict:                    dp[i] = True        return dp[len(s)]

 

转载地址:http://qvtym.baihongyu.com/

你可能感兴趣的文章
列表字典推导式
查看>>
HDOJ 1228 A+B(map水题)
查看>>
intellij IDEA 导入包的方法·
查看>>
Python之路番外:PYTHON基本数据类型和小知识点
查看>>
转:matlab+spider+weka
查看>>
步步为营 .NET 设计模式学习笔记 十五、Composite(组合模式)
查看>>
angular通过路由实现跳转 resource加载数据
查看>>
python try except, 异常处理
查看>>
字符串中的各种方法
查看>>
创建文件夹、新建txt文件
查看>>
js form表单 鼠标移入弹出提示功能
查看>>
LFS7.10——准备Host系统
查看>>
Redis.py客户端的命令总结【三】
查看>>
mac 安装secureCRT
查看>>
/var/adm/wtmp文件太大该怎么办?
查看>>
反应器模式 vs 观察者模式
查看>>
Algernon's Noxious Emissions POJ1121 zoj1052
查看>>
iOS-数据持久化-对象归档
查看>>
iOS开发UI篇—程序启动原理和UIApplication
查看>>
MUI 里js动态添加数字输入框后,增加、减少按钮无效
查看>>