标签:into dict problems sep cat begin ret log ted
原题地址:
https://leetcode.com/problems/word-break/description/
题目:
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"
.
解法:
这道题目利用动态规划做出来,不得不说想法是很巧妙的,我也是参考了网上的代码才AC了。因此,先放代码,等我完全弄懂再补充吧:
class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { if(s == "" || s.size() == 0) { return true; } unordered_map<int, bool> res; for (int i = 0; i <= s.size(); i++) { res[i] = false; } res[0] = true; for (int i = 0; i < s.size(); i++) { string str = s.substr(0, i + 1); for (int j = 0; j <= i; j++) { if (res[j] && find(wordDict.begin(), wordDict.end(), str) != wordDict.end()) { res[i + 1] = true; break; } str = str.substr(1, str.size() - 1); } } return res[s.size()]; } };
标签:into dict problems sep cat begin ret log ted
原文地址:http://www.cnblogs.com/fengziwei/p/7678271.html