e.g., bedbathandbeyond into bed bath and beyond, also bed bat hand beyond
Classical DP:
actually very simple DP, only need to check if T[j] is one, then S[j+1...i] is a word or not
Code:
vector
{
vector
for (int i=0; i
// set T[i] if s(0,i) is a valid word
if (dict.find(s.substr(0, i+1)) != dict.cend() ) T[i] = i+1;
// set T[i] if T[j]!=0 and s(j+1, i) is a valid word
for (int j=0; j if (T[j]!=0 && dict.find( s.substr(j+1, i-j))!=dict.cend() )
T[i] = i-j;
}
vector
if ( T.back() )
{
int idx = s.size() - 1;
while(idx >=0)
{
ret.emplace_back(s.substr(idx - T[idx] +1 , T[idx]) );
idx -= T[idx];
}
reverse(ret.begin(), ret.end());
}
return ret;
}
No comments:
Post a Comment