C ++ Write a Program That Reads a Sequence of Words Then Print Them in a Box

Given an input cord and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of lexicon words. Meet following examples for more details.
This is a famous Google interview question, as well beingness asked by many other companies now a days.

Consider the following dictionary  { i, like, sam, sung, samsung, mobile, ice,    cream, icecream, homo, go, mango}  Input:  ilike Output: Yep  The string tin be segmented as "i like".  Input:  ilikesamsung Output: Yep The string can be segmented equally "i like samsung"  or "i like sam sung".

Recursive implementation:
The thought is elementary, we consider each prefix and search information technology in dictionary. If the prefix is present in lexicon, nosotros recur for rest of the string (or suffix).

Python3

def wordBreak(wordList, discussion):

if word = = '':

render True

else :

wordLen = len (discussion)

return any ([(word[:i] in wordList) and wordBreak(wordList, discussion[i:]) for i in range ( i , wordLen + ane )])

If the recursive phone call for suffix returns true, we return true, otherwise we try next prefix. If nosotros accept tried all prefixes and none of them resulted in a solution, we return false.
We strongly recommend to meet substr function which is used extensively in following implementations.

C++

#include <iostream>

using namespace std;

int dictionaryContains(string word)

{

string dictionary[] = { "mobile" , "samsung" , "sam" , "sung" ,

"human" , "mango" , "icecream" , "and" ,

"go" , "i" , "like" , "ice" , "foam" };

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) render true ;

for ( int i=one; i<=size; i++)

{

if (dictionaryContains( str.substr(0, i) ) &&

wordBreak( str.substr(i, size-i) ))

return truthful ;

}

render fake ;

}

int primary()

{

wordBreak( "ilikesamsung" )? cout << "Yes\n" : cout << "No\north" ;

wordBreak( "iiiiiiii" )? cout << "Yes\northward" : cout << "No\northward" ;

wordBreak( "" )? cout << "Aye\n" : cout << "No\n" ;

wordBreak( "ilikelikeimangoiii" )? cout << "Yeah\n" : cout << "No\n" ;

wordBreak( "samsungandmango" )? cout << "Yes\n" : cout << "No\n" ;

wordBreak( "samsungandmangok" )? cout << "Yes\n" : cout << "No\due north" ;

render 0;

}

Coffee

import java.util.*;

public class WordBreakProblem

{

individual static Prepare<String> dictionary = new HashSet<>();

public static void main(String []args)

{

String temp_dictionary[] = { "mobile" , "samsung" , "sam" , "sung" ,

"man" , "mango" , "icecream" , "and" ,

"go" , "i" , "like" , "water ice" , "cream" };

for (Cord temp :temp_dictionary)

{

dictionary.add(temp);

}

System.out.println(wordBreak( "ilikesamsung" ));

System.out.println(wordBreak( "iiiiiiii" ));

Organization.out.println(wordBreak( "" ));

System.out.println(wordBreak( "ilikelikeimangoiii" ));

System.out.println(wordBreak( "samsungandmango" ));

Organization.out.println(wordBreak( "samsungandmangok" ));

}

public static boolean wordBreak(Cord word)

{

int size = word.length();

if (size == 0 )

return true ;

for ( int i = 1 ; i <= size; i++)

{

if (dictionary.contains(give-and-take.substring( 0 ,i)) &&

wordBreak(word.substring(i,size)))

render true ;

}

return fake ;

}

}

Output

Yes Yes Yeah Yes Yes No

Dynamic Programming
Why Dynamic Programming? The above problem exhibits overlapping sub-bug. For example, run across the following fractional recursion tree for cord "abcde" in worst case.

wordBreak

CPP

#include <iostream>

#include <cord.h>

using namespace std;

int dictionaryContains(string word)

{

cord lexicon[] = { "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" ,

"icecream" , "and" , "go" , "i" , "like" , "ice" , "foam" };

int size = sizeof (dictionary)/ sizeof (lexicon[0]);

for ( int i = 0; i < size; i++)

if (dictionary[i].compare(discussion) == 0)

return true ;

return imitation ;

}

bool wordBreak(string str)

{

int size = str.size();

if (size == 0) return true ;

bool wb[size+1];

memset (wb, 0, sizeof (wb));

for ( int i=1; i<=size; i++)

{

if (wb[i] == false && dictionaryContains( str.substr(0, i) ))

wb[i] = true ;

if (wb[i] == true )

{

if (i == size)

return true ;

for ( int j = i+1; j <= size; j++)

{

if (wb[j] == faux && dictionaryContains( str.substr(i, j-i) ))

wb[j] = true ;

if (j == size && wb[j] == true )

render true ;

}

}

}

render imitation ;

}

int master()

{

wordBreak( "ilikesamsung" )? cout << "Yep\n" : cout << "No\n" ;

wordBreak( "iiiiiiii" )? cout << "Yes\n" : cout << "No\due north" ;

wordBreak( "" )? cout << "Yes\n" : cout << "No\northward" ;

wordBreak( "ilikelikeimangoiii" )? cout << "Yeah\north" : cout << "No\due north" ;

wordBreak( "samsungandmango" )? cout << "Aye\n" : cout << "No\northward" ;

wordBreak( "samsungandmangok" )? cout << "Yes\n" : cout << "No\due north" ;

return 0;

}

Java

import java.util.*;

class GFG{

static boolean dictionaryContains(String word)

{

Cord lexicon[] = { "mobile" , "samsung" , "sam" , "sung" , "human" , "mango" ,

"icecream" , "and" , "get" , "i" , "like" , "ice" , "cream" };

int size = dictionary.length;

for ( int i = 0 ; i < size; i++)

if (dictionary[i].compareTo(word) == 0 )

return true ;

return false ;

}

static boolean wordBreak(String str)

{

int size = str.length();

if (size == 0 ) return truthful ;

boolean []wb = new boolean [size+ ane ];

for ( int i= 1 ; i<=size; i++)

{

if (wb[i] == false && dictionaryContains( str.substring( 0 , i) ))

wb[i] = truthful ;

if (wb[i] == truthful )

{

if (i == size)

render truthful ;

for ( int j = i+ 1 ; j <= size; j++)

{

if (wb[j] == false && dictionaryContains( str.substring(i, j) ))

wb[j] = true ;

if (j == size && wb[j] == true )

return true ;

}

}

}

return false ;

}

public static void main(String[] args)

{

if (wordBreak( "ilikesamsung" ))

System.out.print( "Yes\n" );

else

System.out.print( "No\n" );

if (wordBreak( "iiiiiiii" ))

System.out.print( "Yes\n" );

else

System.out.print( "No\due north" );

if (wordBreak( "" ))

System.out.print( "Yes\northward" );

else

Organization.out.print( "No\n" );

if (wordBreak( "ilikelikeimangoiii" ))

Organization.out.print( "Yeah\n" );

else

Arrangement.out.print( "No\n" );

if (wordBreak( "samsungandmango" ))

System.out.print( "Yes\n" );

else

System.out.print( "No\n" );

if (wordBreak( "samsungandmangok" ))

Arrangement.out.print( "Yes\n" );

else

System.out.impress( "No\n" );

}

}

Output

Yes Yep Yes Yes Yeah No

Optimized Dynamic Programming:
In this approach, apart from the dp table, we besides maintain all the indexes which have matched before. Then nosotros will bank check the substrings from those indexes to the current index. If anyone of that matches then we can divide the string upwardly to that index.
In this program, nosotros are using some extra space. Notwithstanding, its fourth dimension complexity is O(n*south) where south is the length of the largest string in the dictionary and n is the length of the given string.

CPP

#include <bits/stdc++.h>

using namespace std;

int dictionaryContains(string word)

{

string dictionary[]

= { "mobile" , "samsung" , "sam" , "sung" , "human" ,

"mango" , "icecream" , "and" , "go" , "i" ,

"like" , "ice" , "cream" };

int size = sizeof (dictionary) / sizeof (lexicon[0]);

for ( int i = 0; i < size; i++)

if (dictionary[i].compare(discussion) == 0)

return truthful ;

render simulated ;

}

bool wordBreak(string south)

{

int northward = s.size();

if (northward == 0)

render true ;

vector< bool > dp(n + 1, 0);

vector< int > matched_index;

matched_index.push_back(-one);

for ( int i = 0; i < n; i++) {

int msize = matched_index.size();

int f = 0;

for ( int j = msize - 1; j >= 0; j--) {

string sb = s.substr(matched_index[j] + 1,

i - matched_index[j]);

if (dictionaryContains(sb)) {

f = ane;

break ;

}

}

if (f == 1) {

dp[i] = i;

matched_index.push_back(i);

}

}

return dp[north - 1];

}

int main()

{

wordBreak( "ilikesamsung" ) ? cout << "Aye\n"

: cout << "No\n" ;

wordBreak( "iiiiiiii" ) ? cout << "Yes\northward"

: cout << "No\n" ;

wordBreak( "" ) ? cout << "Yeah\northward" : cout << "No\north" ;

wordBreak( "ilikelikeimangoiii" ) ? cout << "Yes\n"

: cout << "No\due north" ;

wordBreak( "samsungandmango" ) ? cout << "Yes\north"

: cout << "No\northward" ;

wordBreak( "samsungandmangok" ) ? cout << "Yeah\n"

: cout << "No\n" ;

render 0;

}

Java

import coffee.io.*;

import java.util.*;

form GFG {

public static boolean wordBreak(String s, List<String> dictionary) {

boolean [] dp = new boolean [s.length() + 1 ];

dp[ 0 ] = true ;

for ( int i = 0 ; i <= s.length(); i++){

for ( int j = 0 ; j < i; j++){

if (dp[j] && dictionary.contains(s.substring(j, i))){

dp[i] = truthful ;

break ;

}

}

}

return dp[southward.length()];

}

public static void main (String[] args) {

String[] dictionary = { "mobile" , "samsung" , "sam" , "sung" , "human" ,

"mango" , "icecream" , "and" , "go" , "i" ,

"similar" , "water ice" , "cream" };

List<String> dict = new ArrayList<>();

for (String s : dictionary){

dict.add(s);

}

if (wordBreak( "ilikesamsung" , dict)) {

Organization.out.println( "Yes" );

} else {

System.out.println( "No" );

}

if (wordBreak( "iiiiiiii" , dict)) {

System.out.println( "Yes" );

} else {

Organization.out.println( "No" );

}

if (wordBreak( "" , dict)) {

Organisation.out.println( "Yes" );

} else {

System.out.println( "No" );

}

if (wordBreak( "samsungandmango" , dict)) {

System.out.println( "Yes" );

} else {

System.out.println( "No" );

}

if (wordBreak( "ilikesamsung" , dict)) {

Organization.out.println( "Yes" );

} else {

Arrangement.out.println( "No" );

}

if (wordBreak( "samsungandmangok" , dict)) {

Arrangement.out.println( "Yep" );

} else {

Arrangement.out.println( "No" );

}

}

}

Javascript

<script>

function wordBreak( southward, lexicon)

{

var dp = Array(southward.length + 1).fill up( false );

dp[0] = true ;

for ( var i = 0; i <= s.length; i++) {

for ( var j = 0; j < i; j++) {

if (dp[j] && lexicon.has(due south.substring(j, i))) {

dp[i] = true ;

break ;

}

}

}

return dp[s.length];

}

var lexicon = [ "mobile" , "samsung" , "sam" , "sung" , "human being" , "mango" , "icecream" , "and" , "go" , "i" ,

"similar" , "ice" , "cream" ];

var dict = new Set();

for ( var s of dictionary) {

dict.add together(s);

}

if (wordBreak( "ilikesamsung" , dict)) {

certificate.write( "<br/>Yes" );

} else {

document.write( "<br/>No" );

}

if (wordBreak( "iiiiiiii" , dict)) {

certificate.write( "<br/>Yes" );

} else {

document.write( "<br/>No" );

}

if (wordBreak( "" , dict)) {

document.write( "<br/>Yes" );

} else {

document.write( "<br/>No" );

}

if (wordBreak( "samsungandmango" , dict)) {

certificate.write( "<br/>Yes" );

} else {

document.write( "<br/>No" );

}

if (wordBreak( "ilikesamsung" , dict)) {

document.write( "<br/>Yes" );

} else {

certificate.write( "<br/>No" );

}

if (wordBreak( "samsungandmangok" , dict)) {

document.write( "<br/>Yes" );

} else {

document.write( "<br/>No" );

}

</script>

Output

Yes Yes Yes Yep Yes No

Word Break Trouble | (Trie solution)
Practice:
The in a higher place solutions merely finds out whether a given string tin can be segmented or not. Extend the above Dynamic Programming solution to print all possible partitions of input string.
Examples:

Input: ilikeicecreamandmango Output:  i like water ice foam and man get i like water ice cream and mango i like icecream and man get i like icecream and mango  Input: ilikesamsungmobile Output: i like sam sung mobile i like samsung mobile

Refer below post for solution of do.
Word Break Problem using Backtracking
Delight write comments if you notice anything incorrect, or you want to share more data about the topic discussed in a higher place


kurtzuponce.blogspot.com

Source: https://www.geeksforgeeks.org/word-break-problem-dp-32/

0 Response to "C ++ Write a Program That Reads a Sequence of Words Then Print Them in a Box"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel