Leetcode: Word Break
来源:互联网 发布:php 去除数组重复元素 编辑:程序博客网 时间:2024/06/02 14:27
题目:
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”.
思路分析:
按照官方的解法:动态规划(Dynamic Programming)
感觉自己对动态规划问题还是不能熟练应对。不能准确找出变量之间的递推关系。
设F(0, i)表示前i个子串分割后是否存在于字典中。那么,这道题中存在这样的递推关系:F(0, i) = F(0, j) + F(j, i),即前i个字符结果为true的充分条件是前j个字符结果为true,第j到i个子串结果也是true。
C++参考代码:
class Solution{public: bool wordBreak(string s, unordered_set<string> &dict) { string::size_type size = s.size(); //申请size+1大小的空间,第一个设为true vector<bool> matches(size + 1, false); matches[0] = true; for (size_t i = 1; i <= size; ++i) { for (size_t j = 0; j < i; ++j) { if (matches[j] && (dict.count(s.substr(j, i - j)) > 0)) { matches[i] = true; break; } } } return matches[size]; }};
C#参考代码:
public class Solution{ public bool WordBreak(string s, ISet<string> dict) { bool[] matches = new bool[s.Length + 1]; matches[0] = true; for (int i = 1; i <= s.Length; ++i) { for (int j = 0; j < i; ++j) { if (matches[j] && dict.Contains(s.Substring(j, i - j))) { matches[i] = true; break; } } } return matches[s.Length]; }}
0 0
- leetcode Word Break & Word Break ||
- Leetcode: Word Break
- [leetcode]Word Break
- [leetcode]Word Break II
- LeetCode:Word Break
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break
- [LeetCode] Word Break II
- LeetCode: Word Break
- leetcode之Word Break
- [LeetCode]Word Break II
- [LeetCode]Word Break
- leetcode-Word Break
- LeetCode 之 Word Break
- leetcode word break
- LeetCode | Word Break
- LeetCode | Word Break II
- 第10题:翻转句子中单词的顺序
- Google推荐的图片加载库Glide介绍
- [HNOI2004]打鼹鼠 解题报告
- 转:could not find the main class, Program will exit (说明编译器compiler版本要不高于installed JREs,JVM版本)
- [CookBook_V2 笔记]字符和字符值之间的转换[1-2]
- Leetcode: Word Break
- 德莱联盟
- WebService介绍
- C++中struct和class的区别及C++ this变量和const变量类型
- 最长公共子序列求解:递归与动态规划方法
- Max Points on a Line
- 《Linux/UNIX系统编程手册》 英文版读书笔记 Alternative I/O Models63.2
- VS2010 Qt代码提示
- 烤鸭的gerrit使用总结