35#include <unordered_set>
61 const std::unordered_set<std::string> &strSet) {
62 return strSet.find(str) != strSet.end();
80bool check(
const std::string &s,
const std::unordered_set<std::string> &strSet,
81 int pos, std::vector<int> *
dp) {
82 if (pos == s.length()) {
89 if (
dp->at(pos) != INT_MAX) {
93 return dp->at(pos) == 1;
96 std::string wordTillNow =
99 for (
int i = pos; i < s.length(); i++) {
103 std::string(1, s[i]);
108 if (
exists(wordTillNow, strSet) && check(s, strSet, i + 1,
dp)) {
131bool wordBreak(
const std::string &s,
const std::vector<std::string> &wordDict) {
134 std::unordered_set<std::string> strSet;
135 for (
const auto &s : wordDict) {
141 std::vector<int>
dp(s.length(), INT_MAX);
146 return check(s, strSet, 0, &
dp);
158 const std::string s =
"applepenapple";
160 const std::vector<std::string> wordDict = {
"apple",
"pen"};
162 assert(dynamic_programming::word_break::wordBreak(s, wordDict));
166 std::cout << dynamic_programming::word_break::wordBreak(s, wordDict)
168 std::cout <<
"Test implementation passed!\n";
178 const std::string s =
"applepenapple";
180 const std::vector<std::string> wordDict = {
"apple",
"pen"};
184 std::cout << dynamic_programming::word_break::wordBreak(s, wordDict)
Dynamic Programming algorithms.
Functions for Word Break problem.
bool exists(const std::string &str, const std::unordered_set< std::string > &strSet)
Function that checks if the string passed in param is present in the the unordered_set passed.
static void test()
Test implementations.
bool wordBreak(const std::string &s, const std::vector< std::string > &wordDict)
Function that checks if the string passed in param can be segmented into the strings present in the v...