一眼暴力,发现根本做不了,想着想着,发现 dpdpdp 很好想,来试试。

枚举字符串 sss 的所有位置作为起始点,如图状态转移。
规定 : f[0]f[0]f[0] 表示空字符的集合,可以用空串组成,所以 f[0]=truef[0]=truef[0]=true
提示 : 字符串哈希可以 O(1)O(1)O(1) 时间内查找字符串是否出现。
class Solution {
public:bool wordBreak(string s, vector& wordDict) {typedef unsigned long long ULL;const int p = 131;unordered_set hash;for(auto &word:wordDict){ULL h = 0;for(auto &c:word)h = h*p + c;hash.insert(h);}const int n = s.size();s = ' ' + s;vector f(n+1,false);f[0] = true;//空字符可以被组成for(int i = 0 ; i//1~i可以组成ULL h = 0;//从i+1到j计算哈希值for(int j = i + 1;j<=n;j++){h = h*p + s[j];if(hash.count(h)) f[j] = true;}}return f[n];}
};
