LeetCode-Word Break
2013-10-06 00:40
337 查看
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 =
dict =
Return true because
方法1 kmp+动归 复杂度O(n*L) n为字符串长度,L为字典大小
View Code
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
方法1 kmp+动归 复杂度O(n*L) n为字符串长度,L为字典大小
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { // Note: The Solution object is instantiated only once and is reused by each test case. int maxLen=0; for(unordered_set<string>::iterator it=dict.begin();it!=dict.end();it++){ if( (*it).length()>maxLen)maxLen=(*it).length(); } string tmp; vector<bool>acc; acc.resize(s.length()+1,false); acc[0]=true; for(int i=0;i<s.length();i++){ if(acc[i]){ int top=min(maxLen,(int)s.length()-i); for(int j=1;j<=top;j++){ tmp=s.substr(i,j); if(dict.find(tmp)!=dict.end()){ acc[i+j]=true; } } } } return acc[s.length()]; } };
View Code
相关文章推荐
- leetcode-Word Break
- LeetCode-139. Word Break
- [leetcode]139. Word Break
- LeetCode: Word Break
- [Leetcode][JAVA] Word Break
- [leetcode] 139 Word Break
- leetcode 139. Word Break(dp,字典匹配)
- LeetCode _ Word Break
- LeetCode139:Word Break
- [LeetCode]Word Break
- 【LeetCode】Word Break 动态规划
- [LeetCode]Word Break
- [LeetCode] 139. Word Break 单词拆分
- LeetCode 139. Word Break
- Word Break----leetcode
- Word Break--LeetCode
- 【LeetCode-面试算法经典-Java实现】【139-Word Break(单词拆分)】
- [leetcode][DP] Word Break
- Leetcode_DP_Word Break
- LeetCode139:Word Break