#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// Check if word is in dictionary
bool isInDict(const char* word, const char* dict[], int dictSize) {
for (int i = 0; i < dictSize; i++) {
if (strcmp(word, dict[i]) == 0) {
return true;
}
}
return false;
}
// Word Break function using recursion and memoization
bool wordBreakHelper(const char* s, const char* dict[], int dictSize, int start, int memo[]) {
int len = strlen(s);
if (start == len) {
return true; // reached end successfully
}
if (memo[start] != -1) {
return memo[start]; // return cached result
}
for (int end = start + 1; end <= len; end++) {
int subLen = end - start;
char sub[subLen + 1];
strncpy(sub, s + start, subLen);
sub[subLen] = '\0';
if (isInDict(sub, dict, dictSize)) {
if (wordBreakHelper(s, dict, dictSize, end, memo)) {
memo[start] = 1;
return true;
}
}
}
memo[start] = 0;
return false;
}
bool wordBreak(const char* s, const char* dict[], int dictSize) {
int len = strlen(s);
int memo[len];
for (int i = 0; i < len; i++) {
memo[i] = -1; // -1 means not computed
}
return wordBreakHelper(s, dict, dictSize, 0, memo);
}
int main() {
const char* dict[] = {"word", "break", "problem"};
const char* s = "wordbreak";
if (wordBreak(s, dict, 3)) {
printf("word break possible\n");
} else {
printf("word break not possible\n");
}
return 0;
}
if (start == len) { return true; }
base case: reached end means successful segmentation
if (memo[start] != -1) { return memo[start]; }
use memo to avoid repeated work
for (int end = start + 1; end <= len; end++) { ... }
try all prefixes from current start
if (isInDict(sub, dict, dictSize)) { if (wordBreakHelper(...)) { memo[start] = true; return true; } }
if prefix is word and suffix can be segmented, mark true and return
memo[start] = false; return false;
no valid segmentation found from this start