samedi 18 avril 2015

Recursion? Combinations in a String

Hello people of the Stackoverflow community. I've been dealing with the following recursion question for a while now and still wasn't able to figure it out. Basically, you have some sort of a sentence (all words are just jammed together, not spaced out) made out of certain words. The idea is to find the number of all possible combinations of words that can be used to create a sentence.


For example,


Words:



ook, ookook


Sentence:



ookookook


There are three ways to make this sentence: {ok, ok, ok}, {ookook, ok}, {ok, ookook}.


Another example,


Words:



ooga, oogam, oogum, mook, ook


Sentence:



oogamookoogumook


There are two ways to make this sentence: {ooga, mook, oogum, ook}, {oogam, ook, oogum, ook}


I've tried a lot of things, lastly I gave up and tried doing it manually...



public static int WAYS(String word) {
int ways = 1;
for (int i = 0; i < word.length(); i++) {
try{
if(word.substring(i, i - 2).equals("ug")){
if(word.substring(i - 4, i - 2).equals("ug")){
ways++;
}
}
else if(word.substring(i, i - 3).contains("ook")){
System.out.println(word.substring(i-6, i-3));
if(word.substring(i - 6, i - 3).equals("ook")){
ways++;
}
if(word.charAt(i - 4) == 'm'){
if(word.substring(i - 8, i - 4).equals("ooga") || word.substring(i - 8, i - 4).equals("oogu")){
ways++;
}
}
}
else if(word.substring(i, i - 4).contains("mook")){
if(word.substring(i - 8, i - 4).contains("mook")){
ways++;
}
}
if(word.substring(i, i - 2).equals("oog")){
if(word.charAt(i + 2) == 'm'){
if(word.charAt(i + 1) == 'a' || word.charAt(i + 1) == 'u'){
ways++;
}
}
}
} catch(Exception e){
continue;
}
}
return ways;
}


But it hasn't worked. Could somebody please give me an idea or a sample on approaching this problem using recursion or dynamic programming. It would be greatly appreciated..


Thanks!


Aucun commentaire:

Enregistrer un commentaire