Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
This is a famous Google interview question, also being asked by many other companies now a days.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
Input: ilikesamsung
Output: Yes
The string can be segmented as "i like samsung"
or "i like sam sung".
Recursive implementation:
The idea is simple, we consider each prefix and search for it in dictionary. If the prefix is present in dictionary, we recur for rest of the string (or suffix).
C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool WordBreak( const vector<string>& wordList,
const string& word)
{
if (word.empty())
return true ;
int wordLen = word.length();
for ( int i = 1; i <= wordLen; ++i) {
string prefix = word.substr(0, i);
if (find(wordList.begin(), wordList.end(), prefix)
!= wordList.end()
&& WordBreak(wordList, word.substr(i))) {
return true ;
}
}
return false ;
}
int main()
{
vector<string> wordList
= { "mobile" , "samsung" , "sam" , "sung" , "man" ,
"mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" };
bool result = WordBreak(wordList, "ilikesamsung" );
cout << boolalpha << result << endl;
return 0;
}
|
Python3
def wordBreak(wordList, word):
if word = = '':
return True
else :
wordLen = len (word)
return any ([(word[:i] in wordList) and wordBreak(wordList, word[i:]) for i in range ( 1 , wordLen + 1 )])
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
public static bool WordBreak(List< string > wordList,
string word)
{
if (word == "" )
return true ;
int wordLen = word.Length;
return Enumerable.Range(1, wordLen)
.Any(i
=> wordList.Contains(word.Substring(0, i))
&& WordBreak(wordList,
word.Substring(i)));
}
public static void Main( string [] args)
{
Console.WriteLine(WordBreak(
new List< string >( new string [] {
"mobile" , "samsung" , "sam" , "sung" , "man" ,
"mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" }),
"ilikesamsung" ));
}
}
|
If the recursive call for suffix returns true, we return true, otherwise we try next prefix. If we have tried all prefixes and none of them resulted in a solution, we return false.
We strongly recommend to see 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" ,
"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 ;
for ( int i=1; i<=size; i++)
{
if (dictionaryContains( str.substr(0, i) ) &&
wordBreak( str.substr(i, size-i) ))
return true ;
}
return false ;
}
int main()
{
wordBreak( "ilikesamsung" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "iiiiiiii" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "ilikelikeimangoiii" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "samsungandmango" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "samsungandmangok" )? cout << "Yes\n" : cout << "No\n" ;
return 0;
}
|
Java
import java.util.*;
public class WordBreakProblem
{
private static Set<String> dictionary = new HashSet<>();
public static void main(String []args)
{
String temp_dictionary[] = { "mobile" , "samsung" , "sam" , "sung" ,
"man" , "mango" , "icecream" , "and" ,
"go" , "i" , "like" , "ice" , "cream" };
for (String temp :temp_dictionary)
{
dictionary.add(temp);
}
System.out.println(wordBreak( "ilikesamsung" ));
System.out.println(wordBreak( "iiiiiiii" ));
System.out.println(wordBreak( "" ));
System.out.println(wordBreak( "ilikelikeimangoiii" ));
System.out.println(wordBreak( "samsungandmango" ));
System.out.println(wordBreak( "samsungandmangok" ));
}
public static boolean wordBreak(String word)
{
int size = word.length();
if (size == 0 )
return true ;
for ( int i = 1 ; i <= size; i++)
{
if (dictionary.contains(word.substring( 0 ,i)) &&
wordBreak(word.substring(i,size)))
return true ;
}
return false ;
}
}
|
Python3
def wordBreak(word):
global dictionary
size = len (word)
if (size = = 0 ):
return True
for i in range ( 1 ,size + 1 ):
if (word[ 0 :i] in dictionary and wordBreak(word[i: size])):
return True
return False
dictionary = set ()
temp_dictionary = [ "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" , "like" , "ice" , "cream" ]
for temp in temp_dictionary:
dictionary.add(temp)
print ( "Yes" if wordBreak( "ilikesamsung" ) else "No" )
print ( "Yes" if wordBreak( "iiiiiiii" ) else "No" )
print ( "Yes" if wordBreak(" ") else " No")
print ( "Yes" if wordBreak( "ilikelikeimangoiii" ) else "No" )
print ( "Yes" if wordBreak( "samsungandmango" ) else "No" )
print ( "Yes" if wordBreak( "samsungandmangok" ) else "No" )
|
C#
using System;
using System.Collections.Generic;
public class WordBreakProblem
{
private static HashSet< string > dictionary = new HashSet< string >();
public static bool wordBreak( string word)
{
int size = word.Length;
if (size == 0)
return true ;
for ( int i = 1; i <= size; i++)
{
if (dictionary.Contains(word.Substring(0, i)) &&
wordBreak(word.Substring(i, size - i)))
return true ;
}
return false ;
}
static void Main( string [] args)
{
string [] temp_dictionary = { "mobile" , "samsung" , "sam" , "sung" ,
"man" , "mango" , "icecream" , "and" ,
"go" , "i" , "like" , "ice" , "cream" };
foreach ( string temp in temp_dictionary)
{
dictionary.Add(temp);
}
Console.WriteLine(wordBreak( "ilikesamsung" ));
Console.WriteLine(wordBreak( "iiiiiiii" ));
Console.WriteLine(wordBreak( "" ));
Console.WriteLine(wordBreak( "ilikelikeimangoiii" ));
Console.WriteLine(wordBreak( "samsungandmango" ));
Console.WriteLine(wordBreak( "samsungandmangok" ));
}
}
|
Javascript
<script>
var dictionary = new Set();
var temp_dictionary = [ "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" ];
for ( var temp of temp_dictionary) {
dictionary.add(temp);
}
document.write(((wordBreak( "ilikesamsung" ))? "Yes" : "No" )+ "<br/>" );
document.write(((wordBreak( "iiiiiiii" ))? "Yes" : "No" )+ "<br/>" );
document.write(((wordBreak( "" ))? "Yes" : "No" )+ "<br/>" );
document.write(((wordBreak( "ilikelikeimangoiii" ))? "Yes" : "No" )+ "<br/>" );
document.write(((wordBreak( "samsungandmango" ))? "Yes" : "No" )+ "<br/>" );
document.write(((wordBreak( "samsungandmangok" ))? "Yes" : "No" )+ "<br/>" );
function wordBreak( word) {
var size = word.length;
if (size == 0)
return true ;
for ( var i = 1; i <= size; i++) {
if (dictionary.has(word.substring(0, i)) && wordBreak(word.substring(i, size)))
return true ;
}
return false ;
}
</script>
|
OutputYes
Yes
Yes
Yes
Yes
No
Time Complexity: The time complexity of the above code will be O(2^n).
Auxiliary Space: The space complexity will be O(n) as we are using recursion and the recursive call stack will take O(n) space.
Dynamic Programming
Why Dynamic Programming? The above problem exhibits overlapping sub-problems. For example, see the following partial recursion tree for string “abcde” in the worst case.

CPP
#include <iostream>
#include <string.h>
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[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] == false && dictionaryContains( str.substr(i, j-i) ))
wb[j] = true ;
if (j == size && wb[j] == true )
return true ;
}
}
}
return false ;
}
int main()
{
wordBreak( "ilikesamsung" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "iiiiiiii" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "ilikelikeimangoiii" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "samsungandmango" )? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "samsungandmangok" )? cout << "Yes\n" : cout << "No\n" ;
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean dictionaryContains(String word)
{
String dictionary[] = { "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" ,
"icecream" , "and" , "go" , "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 true ;
boolean []wb = new boolean [size+ 1 ];
for ( int i= 1 ; i<=size; i++)
{
if (wb[i] == false && dictionaryContains( str.substring( 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] == 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\n" );
if (wordBreak( "" ))
System.out.print( "Yes\n" );
else
System.out.print( "No\n" );
if (wordBreak( "ilikelikeimangoiii" ))
System.out.print( "Yes\n" );
else
System.out.print( "No\n" );
if (wordBreak( "samsungandmango" ))
System.out.print( "Yes\n" );
else
System.out.print( "No\n" );
if (wordBreak( "samsungandmangok" ))
System.out.print( "Yes\n" );
else
System.out.print( "No\n" );
}
}
|
Python3
def dictionaryContains(word):
dictionary = [ "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" ]
size = len (dictionary)
for i in range (size):
if (dictionary[i] = = word):
return True
return False
def wordBreak( Str ):
size = len ( Str )
if (size = = 0 ):
return True
wb = [ False for i in range (size + 1 )]
for i in range ( 1 ,size + 1 ):
if (wb[i] = = False and dictionaryContains( Str [ 0 : i])):
wb[i] = True
if (wb[i] = = True ):
if (i = = size):
return True
for j in range (i + 1 ,size + 1 ):
if (wb[j] = = False and dictionaryContains( Str [i: j])):
wb[j] = True
if (j = = size and wb[j] = = True ):
return True
return False
if (wordBreak( "ilikesamsung" )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "iiiiiiii" )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak("")):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "ilikelikeimangoiii" )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "samsungandmango" )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "samsungandmangok" )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
public class GFG
{
public static bool dictionaryContains(String word)
{
String[] dictionary = { "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" , "like" , "ice" , "cream" };
var size = dictionary.Length;
for ( int i = 0; i < size; i++)
{
if ( string .CompareOrdinal(dictionary[i],word) == 0)
{
return true ;
}
}
return false ;
}
public static bool wordBreak(String str)
{
var size = str.Length;
if (size == 0)
{
return true ;
}
bool [] wb = new bool [size + 1];
for ( int i = 1; i <= size; i++)
{
if (wb[i] == false && GFG.dictionaryContains(str.Substring(0,i-0)))
{
wb[i] = true ;
}
if (wb[i] == true )
{
if (i == size)
{
return true ;
}
for ( int j = i + 1; j <= size; j++)
{
if (wb[j] == false && GFG.dictionaryContains(str.Substring(i,j-i)))
{
wb[j] = true ;
}
if (j == size && wb[j] == true )
{
return true ;
}
}
}
}
return false ;
}
public static void Main(String[] args)
{
if (GFG.wordBreak( "ilikesamsung" ))
{
Console.Write( "Yes\n" );
}
else
{
Console.Write( "No\n" );
}
if (GFG.wordBreak( "iiiiiiii" ))
{
Console.Write( "Yes\n" );
}
else
{
Console.Write( "No\n" );
}
if (GFG.wordBreak( "" ))
{
Console.Write( "Yes\n" );
}
else
{
Console.Write( "No\n" );
}
if (GFG.wordBreak( "ilikelikeimangoiii" ))
{
Console.Write( "Yes\n" );
}
else
{
Console.Write( "No\n" );
}
if (GFG.wordBreak( "samsungandmango" ))
{
Console.Write( "Yes\n" );
}
else
{
Console.Write( "No\n" );
}
if (GFG.wordBreak( "samsungandmangok" ))
{
Console.Write( "Yes\n" );
}
else
{
Console.Write( "No\n" );
}
}
}
|
Javascript
<script>
function dictionaryContains( word) {
var dictionary = [ "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" ];
var size = dictionary.length;
for ( var i = 0; i < size; i++)
if (dictionary[i]===(word))
return true ;
return false ;
}
function wordBreak( str) {
var size = str.length;
if (size == 0)
return true ;
var wb = Array(size + 1).fill( false );
for ( var i = 1; i <= size; i++) {
if (wb[i] == false && dictionaryContains(str.substring(0, i)))
wb[i] = true ;
if (wb[i] == true ) {
if (i == size)
return true ;
for (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 ;
}
if (wordBreak( "ilikesamsung" ))
document.write( "Yes<br/>" );
else
document.write( "No<br/>" );
if (wordBreak( "iiiiiiii" ))
document.write( "Yes<br/>" );
else
document.write( "No<br/>" );
if (wordBreak( "" ))
document.write( "Yes<br/>" );
else
document.write( "No<br/>" );
if (wordBreak( "ilikelikeimangoiii" ))
document.write( "Yes<br/>" );
else
document.write( "No<br/>" );
if (wordBreak( "samsungandmango" ))
document.write( "Yes<br/>" );
else
document.write( "No<br/>" );
if (wordBreak( "samsungandmangok" ))
document.write( "Yes<br/>" );
else
document.write( "No<br/>" );
</script>
|
OutputYes
Yes
Yes
Yes
Yes
No
The time complexity of the given implementation of the wordBreak function is O(n^3), where n is the length of the input string.
The space complexity of the implementation is O(n), as an extra boolean array of size n+1 is created. Additionally, the dictionary array occupies a space of O(kL), where k is the number of words in the dictionary and L is the maximum length of a word in the dictionary. However, since the dictionary is a constant and small-sized array, its space complexity can be considered negligible. Therefore, the overall space complexity of the implementation is O(n).
Optimized Dynamic Programming:
In this approach, apart from the dp table, we also maintain all the indexes which have matched earlier. Then we will check the substrings from those indexes to the current index. If anyone of that matches then we can divide the string up to that index.
In this program, we are using some extra space. However, its time complexity is O(n*n) if n>s or O(n*s) if s>n where s is the length of the largest string in the dictionary and n is the length of the given string.
C++
#include <bits/stdc++.h>
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 s)
{
int n = s.size();
if (n == 0)
return true ;
vector< bool > dp(n + 1, 0);
vector< int > matched_index;
matched_index.push_back(-1);
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 = 1;
break ;
}
}
if (f == 1) {
dp[i] = 1;
matched_index.push_back(i);
}
}
return dp[n - 1];
}
int main()
{
wordBreak( "ilikesamsung" ) ? cout << "Yes\n"
: cout << "No\n" ;
wordBreak( "iiiiiiii" ) ? cout << "Yes\n"
: cout << "No\n" ;
wordBreak( "" ) ? cout << "Yes\n" : cout << "No\n" ;
wordBreak( "ilikelikeimangoiii" ) ? cout << "Yes\n"
: cout << "No\n" ;
wordBreak( "samsungandmango" ) ? cout << "Yes\n"
: cout << "No\n" ;
wordBreak( "samsungandmangok" ) ? cout << "Yes\n"
: cout << "No\n" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class 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] = true ;
break ;
}
}
}
return dp[s.length()];
}
public static void main (String[] args) {
String[] dictionary = { "mobile" , "samsung" , "sam" , "sung" , "man" ,
"mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" };
List<String> dict = new ArrayList<>();
for (String s : dictionary){
dict.add(s);
}
if (wordBreak( "ilikesamsung" , dict)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
if (wordBreak( "iiiiiiii" , dict)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
if (wordBreak( "" , dict)) {
System.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)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
if (wordBreak( "samsungandmangok" , dict)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
}
|
Python3
def wordBreak(s, dictionary):
dp = [ False for i in range ( len (s) + 1 )]
dp[ 0 ] = True
for i in range ( len (s) + 1 ):
for j in range (i):
if dp[j] and s[j: i] in dictionary:
dp[i] = True
break
return dp[ len (s)]
dictionary = [ "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" , "like" , "ice" , "cream" ]
dict = set ()
for s in dictionary:
dict .add(s)
if (wordBreak( "ilikesamsung" , dict )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "iiiiiiii" , dict )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak("", dict )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "samsungandmango" , dict )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "ilikesamsung" , dict )):
print ( "Yes" )
else :
print ( "No" )
if (wordBreak( "samsungandmangok" , dict )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
public class WordBreakProgram {
static bool
DictionaryContains(HashSet< string > dictionary,
string word)
{
return dictionary.Contains(word);
}
static bool WordBreak( string s,
HashSet< string > dictionary)
{
int n = s.Length;
if (n == 0)
return true ;
bool [] dp = new bool [n + 1];
List< int > matchedIndex = new List< int >();
matchedIndex.Add(-1);
for ( int i = 0; i < n; i++) {
int msize = matchedIndex.Count;
int f = 0;
for ( int j = msize - 1; j >= 0; j--) {
string sb
= s.Substring(matchedIndex[j] + 1,
i - matchedIndex[j]);
if (DictionaryContains(dictionary, sb)) {
f = 1;
break ;
}
}
if (f == 1) {
dp[i] = true ;
matchedIndex.Add(i);
}
}
return dp[n - 1];
}
public static void Main()
{
HashSet< string > dictionary = new HashSet< string >{
"mobile" , "samsung" , "sam" , "sung" , "man" ,
"mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream"
};
Console.WriteLine(
WordBreak( "ilikesamsung" , dictionary) ? "Yes"
: "No" );
Console.WriteLine(WordBreak( "iiiiiiii" , dictionary)
? "Yes"
: "No" );
Console.WriteLine(WordBreak( "" , dictionary) ? "Yes"
: "No" );
Console.WriteLine(
WordBreak( "ilikelikeimangoiii" , dictionary)
? "Yes"
: "No" );
Console.WriteLine(
WordBreak( "samsungandmango" , dictionary)
? "Yes"
: "No" );
Console.WriteLine(
WordBreak( "samsungandmangok" , dictionary)
? "Yes"
: "No" );
}
}
|
Javascript
<script>
function wordBreak( s, dictionary)
{
var dp = Array(s.length + 1).fill( false );
dp[0] = true ;
for ( var i = 0; i <= s.length; i++) {
for ( var j = 0; j < i; j++) {
if (dp[j] && dictionary.has(s.substring(j, i))) {
dp[i] = true ;
break ;
}
}
}
return dp[s.length];
}
var dictionary = [ "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" ];
var dict = new Set();
for ( var s of dictionary) {
dict.add(s);
}
if (wordBreak( "ilikesamsung" , dict)) {
document.write( "<br/>Yes" );
} else {
document.write( "<br/>No" );
}
if (wordBreak( "iiiiiiii" , dict)) {
document.write( "<br/>Yes" );
} else {
document.write( "<br/>No" );
}
if (wordBreak( "" , dict)) {
document.write( "<br/>Yes" );
} else {
document.write( "<br/>No" );
}
if (wordBreak( "samsungandmango" , dict)) {
document.write( "<br/>Yes" );
} else {
document.write( "<br/>No" );
}
if (wordBreak( "ilikesamsung" , dict)) {
document.write( "<br/>Yes" );
} else {
document.write( "<br/>No" );
}
if (wordBreak( "samsungandmangok" , dict)) {
document.write( "<br/>Yes" );
} else {
document.write( "<br/>No" );
}
</script>
|
OutputYes
Yes
Yes
Yes
Yes
No
Word Break Problem | (Trie solution)
Exercise:
The above solutions only find out whether a given string 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 ice cream and man go
i like ice cream and mango
i like icecream and man go
i like icecream and mango
Input: ilikesamsungmobile
Output:
i like sam sung mobile
i like samsung mobile
Word Break Problem | (Hashmap solution):
In this approach first, we are storing all the words in a Hashmap. after that, we traverse the input string and check if there is a match or not.
C++
#include<bits/stdc++.h>
using namespace std;
bool CanParseUtil(unordered_map<string, bool >mp, string word)
{
int size = word.size();
if (size == 0)
{
return true ;
}
string temp = "" ;
for ( int i = 0; i < word.length(); i++)
{
temp += word[i];
if (mp.find(temp) != mp.end() && CanParseUtil(mp, word.substr(i+1)))
{
return true ;
}
}
return false ;
}
string CanParse(vector<string>words, string word)
{
int start = 0;
unordered_map<string, bool >mp;
for ( auto it : words)
{
mp[it] = true ;
}
return CanParseUtil(mp,word ) == true ? "YES" : "NO" ;
}
int main() {
vector<string>words{ "mobile" , "samsung" , "sam" , "sung" ,
"man" , "mango" , "icecream" , "and" ,
"go" , "i" , "like" , "ice" , "cream" };
string word = "samsungandmangok" ;
cout << CanParse(words, word) << endl;
}
|
Java
import java.util.*;
class GFG {
static boolean CanParseUtil(HashMap<String, Boolean> mp,
String word)
{
int size = word.length();
if (size == 0 ) {
return true ;
}
String temp = "" ;
for ( int i = 0 ; i < word.length(); i++) {
temp += word.charAt(i);
if (mp.containsKey(temp)
&& CanParseUtil(mp,
word.substring(i + 1 ))) {
return true ;
}
}
return false ;
}
static String CanParse(String[] words, String word)
{
HashMap<String, Boolean> mp = new HashMap<>();
for (String it : words) {
mp.put(it, true );
}
return CanParseUtil(mp, word) == true ? "YES"
: "NO" ;
}
public static void main(String[] args)
{
String[] words
= { "mobile" , "samsung" , "sam" , "sung" , "man" ,
"mango" , "icecream" , "and" , "go" , "i" ,
"like" , "ice" , "cream" };
String word = "samsungandmangok" ;
System.out.println(CanParse(words, word));
}
}
|
Python3
def CanParseUtil(mp,word):
size = len (word)
if (size = = 0 ):
return True
temp = ""
for i in range ( len (word)):
temp + = word[i]
if (temp in mp and CanParseUtil(mp, word[i + 1 :])):
return True
return False
def CanParse(words,word):
start = 0
mp = {}
for it in words:
mp[it] = True
return "YES" if CanParseUtil(mp,word ) = = True else "NO"
words = [ "mobile" , "samsung" , "sam" , "sung" ,
"man" , "mango" , "icecream" , "and" ,
"go" , "i" , "like" , "ice" , "cream" ]
word = "samsungandmangok"
print (CanParse(words, word))
|
C#
using System;
using System.Collections.Generic;
class Program {
static bool CanParseUtil(Dictionary< string , bool > mp, string word) {
int size = word.Length;
if (size == 0) {
return true ;
}
string temp = "" ;
for ( int i = 0; i < word.Length; i++) {
temp += word[i];
if (mp.ContainsKey(temp) && CanParseUtil(mp, word.Substring(i+1))) {
return true ;
}
}
return false ;
}
static string CanParse(List< string > words, string word) {
int start = 0;
Dictionary< string , bool > mp = new Dictionary< string , bool >();
foreach ( string it in words) {
mp.Add(it, true );
}
return CanParseUtil(mp, word) == true ? "YES" : "NO" ;
}
static void Main( string [] args) {
List< string > words = new List< string > { "mobile" , "samsung" , "sam" , "sung" , "man" , "mango" , "icecream" , "and" , "go" , "i" , "like" , "ice" , "cream" };
string word = "samsungandmangok" ;
Console.WriteLine(CanParse(words, word));
}
}
|
Javascript
<script>
function CanParseUtil(mp,word)
{
let size = word.length;
if (size == 0)
{
return true ;
}
let temp = "" ;
for (let i = 0; i < word.length; i++)
{
temp += word[i];
if (mp.has(temp) === true && CanParseUtil(mp, word.substring(i+1)))
{
return true ;
}
}
return false ;
}
function CanParse(words,word)
{
let start = 0;
let mp = new Map();
for (let it of words)
{
mp.set(it , true );
}
return CanParseUtil(mp,word ) == true ? "YES" : "NO" ;
}
let words = [ "mobile" , "samsung" , "sam" , "sung" ,
"man" , "mango" , "icecream" , "and" ,
"go" , "i" , "like" , "ice" , "cream" ];
let word = "samsungandmangok" ;
document.write(CanParse(words, word), "</br>" );
</script>
|
Time Complexity: The time complexity of the above code will be O(2^n).
Auxiliary Space: The space complexity will be O(n) as we are using recursion and the recursive call stack will take O(n) space.
Refer below post for solution of exercise.
Word Break Problem using Backtracking
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above