Word Break Problem
Reference:
Recursive version with c(20170101):
#include <stdlib.h>
#include <string.h>
#define MAX_STRING 256
#define IS_EQUAL 0
int dictionaryContains(char *str)
{
char *dictionary[] = { "mobile","samsung","sam","sung","man","mango",
"icecream","and","go","i","like","ice","cream" };
int size = sizeof(dictionary) / sizeof(dictionary[0]);
for (int i = 0; i < size; i++)
if (IS_EQUAL == strcmp(dictionary[i], str))
return true;
return false;
}
bool wordBreak(char *str)
{
int nIndex = 0;
int nStrLen = 0;
nStrLen = strlen(str);
if (nStrLen == 0)
return true;
for (nIndex =1; nIndex<=nStrLen; nIndex++)
{
char sTargetStr[MAX_STRING] = { 0 };
char sSecondStr[MAX_STRING] = { 0 };
strncpy(sTargetStr, str, nIndex);
strncpy(sSecondStr, str+nIndex, nStrLen-nIndex);
if (dictionaryContains(sTargetStr) && wordBreak(sSecondStr))
return true;
}
return false;
}
int main()
{
wordBreak("ilike") ? printf("Yes\n") : printf("No\n"); //yes
wordBreak("iiiiiii") ? printf("Yes\n") : printf("No\n"); //yes
wordBreak("") ? printf("Yes\n") : printf("No\n"); //yes
wordBreak("ilikelikeimangoiii") ? printf("Yes\n") : printf("No\n"); //yes
wordBreak("samsungandmango") ? printf("Yes\n") : printf("No\n"); //yes
wordBreak("samsungandmangok") ? printf("Yes\n") : printf("No\n"); //no
return 0;
}
Iterative version with c:
~~~