Given a string A and a dictionary of n words B, find out if A can be segmented into a space-separated sequence of dictionary words.
Note: From the dictionary B each word can be taken any number of times and in any order.
Example 1:
Input:
n = 12
B = { "i", "like", "sam",
"sung", "samsung", "mobile",
"ice","cream", "icecream",
"man", "go", "mango" }
A = "ilike"
Output:
1
Explanation:
The string can be segmented as "i like".
Example 2:
Input:
n = 12
B = { "i", "like", "sam",
"sung", "samsung", "mobile",
"ice","cream", "icecream",
"man", "go", "mango" }
A = "ilikesamsung"
Output:
1
Explanation:
The string can be segmented as
"i like samsung" or "i like sam sung".
Your Task:
Complete wordBreak() function which takes a string and list of strings as a parameter and returns 1 if it is possible to break words, else return 0. You don't need to read any input or print any output, it is done by driver code.
(https://practice.geeksforgeeks.org/problems/word-break1352/1)
My Answer:
class Sol
{
public static int wordBreak(String A, ArrayList<String> B )
{
//code here
int startIdx = 0;
int len = 0;
String word = null;
Collections.sort(B, Comparator.comparing(String::length).reversed());
for (int i = 0 ; i < B.size() ; i++) {
word = B.get(i);
if (A.contains(word)) {
startIdx = A.indexOf(word);
len = word.length();
A = A.substring(0,startIdx) + A.substring(startIdx+len);
i--;
}
}
if (A.length() == 0) {
return 1;
}
return 0;
}
}