标签:style blog http io color ar 使用 sp for
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"
.
使用breakHere容器表示从字符串是否可以从开头cut到当前位置。
breakHere[i]==true代表从字符串开头到第i个字符结束,存在合理的cut。
典型的动态规划,上代码:
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { if(s.size() == 0) return true; //breakHere[i]==true means workBreak(s.substr(0,i), dict)==true //so workBreak(s, dict) == breakHere[s.size()] vector<bool> breakHere(s.size()+1, false); breakHere[0] = true; //breakHere[i]==true requires: //(1)breakHere[j]==true and //(2)dict.find(s.substr(j, i-j)) != dict.end() for(vector<bool>::size_type i = 1; i < breakHere.size(); i ++) { for(vector<bool>::size_type j = 0; j < i; j ++) { if(breakHere[j]==true && dict.find(s.substr(j, i-j)) != dict.end()) { breakHere[i] = true; break; } } } return breakHere[s.size()]; } };
标签:style blog http io color ar 使用 sp for
原文地址:http://www.cnblogs.com/ganganloveu/p/4101816.html