Leetcode—139. Word Break
来源:互联网 发布:微信淘宝群怎么做到的 编辑:程序博客网 时间:2024/06/07 17:39
问题描述:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
将一个给定的字符串是否可以完全按照字典dict内的元素分解。
解题思路:
两种思路:
考虑可达性的概念,第一种方法是从前向后遍历字符串s,然后计算以当前字符s[ i ] 作为字符子串的首元素,是否在字典Dict中。具体做法为:依次寻找当前位置s[ i ]之后的字符s[ j ], j>i,检验子串s[i……j]是否存在于dict中 。如果存在我们就说 j 位置是可达点。这样一直遍历到最后。如果最后一位为可达点,则返回true。
另一种也是遍历字符串s,但是这一次我们把当前字符s[ i ]作为字符子串的尾元素,即判断 i 之前的所有可达点是和 i 组成字符串,是否在dict内存在,只要有一个存在,就是可达的。
第一种方法比第二种方法效率要低一些,如果我们使用一些简化技巧,比如只有当前位置可达,才开始寻找之后可达点,如果 j 位置的不可达,才进行可达性检验。两种方法的效率应该是差不多的。
下面给出第二种方法的代码:
class Solution {public: bool wordBreak(string s, vector<string>& wordDict) { vector<int> w(s.size()+1); int n = 0; for(int i = 0; i < s.size(); i++) for(int j = n; j>=0; --j){ if(find(wordDict.begin(), wordDict.end(), s.substr(w[j], i-w[j] + 1)) != wordDict.end()){ w[++n] = i+1; break; } } return w[n] == s.size(); }};
- Leetcode—139. Word Break
- LeetCode 139. Word Break
- [LeetCode]139.Word Break
- [leetcode] 139.Word Break
- leetcode 139. Word Break
- [LeetCode]139. Word Break
- 139. Word Break LeetCode
- LeetCode-139.Word Break
- LeetCode *** 139. Word Break
- LeetCode 139. Word Break
- LeetCode 139. Word Break
- [leetcode] 139. Word Break
- [leetcode] 139. Word Break
- [LeetCode] 139. Word Break
- [leetcode]139. Word Break
- Leetcode-139. Word Break
- Leetcode-139. Word Break
- Leetcode 139. Word Break
- 类与类之间的关系
- svn管理idea提交失败代码回退问题
- 数据结构和算法 —— 算法
- 4104:单词翻转
- 2016-2017 HPU暑期集训练习赛
- Leetcode—139. Word Break
- 单调栈(从中间某个位置向左右两侧查找比他大的或者比他小的的边界)
- C语言--ctype.h
- http常见code(40x)
- 用散列表实现学生成绩记录
- 分梨
- HTML学习笔记二
- Struts2笔记
- 安装 Docker Machine