Example 1:
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat"
package pep.Day80;
import java.util.LinkedList;
import java.util.List;
public class LeetCode_648_Replcae_Words {
public static void main(String[] args) {
List<String> dictionary = new LinkedList<>();
dictionary.add("cat");
dictionary.add("bat");
dictionary.add("rat");
String sentence = "the cattle was rattled by the battery";
System.out.println(replaceWords(dictionary, sentence));
}
static class Node {
Node[] children = new Node[26];
String isEnd = null;
}
static Node root = new Node();
public static void insert(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
char tba = word.charAt(i);
if (curr.children[tba - 'a'] == null)
curr.children[tba - 'a'] = new Node();
curr = curr.children[tba - 'a'];
}
curr.isEnd = word;
}
public static String replaceWords(List<String> dictionary, String sentence) {
// dictionary ke sare word TRIES me daal do
for (String word : dictionary) {
insert(word);
}
StringBuilder sb = new StringBuilder();
// sentence ke har word pr jaate hain aur prefix mngwate hain
for (String word : sentence.split(" ")) {
String prefix = getPrefix(word);
if (prefix != null) {
sb.append(prefix);
} else {
sb.append(word);
}
sb.append(" ");
}
return sb.toString().substring(0, sb.length() - 1);
}
private static String getPrefix(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
char tbf = word.charAt(i);
if (curr.children[tbf - 'a'] == null) {
return null;
}
if (curr.children[tbf - 'a'].isEnd != null) {
return curr.children[tbf - 'a'].isEnd;
} else {
curr = curr.children[tbf - 'a'];
}
}
return null;
}
}

No comments:
Post a Comment