Word Break

#include<iostream>
using namespace std;

class wordBreak {
	public:
		void getTxt(string txt) {
			wordBuild(txt, txt.size(), "");
		}

		bool dictionary(string word) {
			string dictionary[] = {"hello", "world", "i", "love", "c", "plus", "plus", "c++", "programming", "java", "python","in"};
			int size = sizeof(dictionary)/sizeof(dictionary[0]);
			for (int i = 0; i < size; i++)

				/* Compare word with dictionary */
				if (dictionary[i].compare(word) == 0)
					return true;
			return false;
		}

		void wordBuild(string str, int size, string result) {

			/* Process all letter one by one */
			for (int i = 1; i <= size; i++) {

				/* Extract substring from 0 to i in sub */
				string sub = str.substr(0, i);
				if (dictionary(sub)) {

					/* if no more letter are there, then print it */
					if (i == size) {

						/* Add this word to previous sub */
						result += sub;
						cout << "\n" << result << endl;
					}
					wordBuild(str.substr(i, size-i), size-i, result+sub+" ");
				}
			}
		}
};

int main() {
	wordBreak wb;
	wb.getTxt("helloworld");
	wb.getTxt("iloveprogramming");
	wb.getTxt("programminginC++");
	wb.getTxt("helloworldinjava");
	wb.getTxt("helloworldprogrammingincplusplus");
	return 0;
}



/* Output */
hello world
i love programming
hello world in java
hello world programming in c plus plus

Comments (0)

  • To add your comment please or

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.

Got It!