Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.
I want get output [a a b c]
.
Why is my code exceeding its time limit and showing no output? I think logic is right.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> dictionary = new ArrayList();
dictionary.add("a");
dictionary.add("b");
dictionary.add("c");
String sentence = new String("aadsfasf absbs bbab cadsfafs");
int i = 0;
int x = 0;
String t = new String();
String h = new String();
while (i < dictionary.size()) {
t = dictionary.get(i);
h = sentence.substring(x);
x = h.indexOf(t);
int g = x;
String ij = new String();
if (x != -1)
while (g < h.length() && h.charAt(g) != ' ') {
ij = ij.concat(Character.toString(h.charAt(g)));
g++;
} else {
i++;
continue;
x = 0;
}
x = x + t.length();
sentence = sentence.replace(ij, t);
}
System.out.println(sentence);
}
}
New contributor
Manish Joshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.