// Word Break Problem.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int dictionaryContains(string word)
{
string 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 (dictionary[i].compare(word) == 0)
return true;
return false;
}
bool wordBreak(string str)
{
int size = str.size();
if (size == 0)
return true;
bool *wb = new bool[size+1];
for (int i = 0; i<= size; i++)
{
wb[i] = false;
}
wb[0] = true;
for (int i = 0; i<size; i++)// idx of the inputed string
{
for (int j = 0; j<=i; j++)
{
if (wb[j] == true)
{
if (dictionaryContains(str.substr(j, i-j+1)))
{
wb[i+1] = true;
break;
}
}
}
}
bool retVal = wb[size] == true? true:false;
delete [] wb;
return retVal;
}
int _tmain(int argc, _TCHAR* argv[])
{
wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n";
wordBreak("iiiiiiii")? cout <<"Yes\n": cout << "No\n";
wordBreak("")? cout <<"Yes\n": cout << "No\n";
wordBreak("ilikelikeimangeiii")? cout <<"Yes\n": cout << "No\n";
wordBreak("samsungandmango")? cout <<"Yes\n": cout << "No\n";
wordBreak("samsungandmangok")? cout <<"Yes\n": cout << "No\n";
return 0;
}