#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAXLEN 256
#define DICTLEN 11
// Check if a word is in the dictionary
bool isInDict(const char* word, const char* dict[], int dictSize) {
for (int i = 0; i < dictSize; i++) {
if (strcmp(dict[i], word) == 0)
return true;
}
return false;
}
// Recursive word break function
void wordBreak(const char* str, int strsize, const char* result, const char* dict[], int dictSize) {
for (int i = 1; i <= strsize; i++) {
char subStr[MAXLEN];
strncpy(subStr, str, i);
subStr[i] = '\0';
if (isInDict(subStr, dict, dictSize)) {
char currentResult[MAXLEN];
if (i == strsize) {
snprintf(currentResult, sizeof(currentResult), "%s%s", result, subStr);
printf("%s\n", currentResult);
return;
} else {
snprintf(currentResult, sizeof(currentResult), "%s%s ", result, subStr);
wordBreak(str + i, strsize - i, currentResult, dict, dictSize);
}
}
}
}
int main() {
const char* dict[] = {
"butterfly", "basketball", "bagpiper", "and", "play",
"with", "butter", "fly", "basket", "ball", "bags"
};
const char* str = "butterflyplaybasketballwithbags";
char result[MAXLEN] = "";
wordBreak(str, strlen(str), result, dict, DICTLEN);
return 0;
}
/*
run:
butter fly play basket ball with bags
butter fly play basketball with bags
butterfly play basket ball with bags
butterfly play basketball with bags
*/