Tue Dec 03 2019
Word Break
C++ Programming1204 views
File Name: word-break.cpp
#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
Reference:
String in C++
Author:Geekboots