najimCseJu

leetcode.com/problems/replace-words/solution/

Oct 27th, 2019
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. class Solution {
  2.     class Trie {
  3.         Map<Character, Trie> children;
  4.         boolean mark;
  5.  
  6.         Trie() {
  7.             children = new HashMap();
  8.             mark = false;
  9.         }
  10.  
  11.         void insert(String s) {
  12.             Trie node = this;
  13.             for (int i = 0; i < s.length(); i++) {
  14.                 char ch = s.charAt(i);
  15.                 if (node.children.containsKey(ch) == false) {
  16.                     Trie newNode = new Trie();
  17.                     node.children.put(ch, newNode);
  18.                 }
  19.                 node = node.children.get(ch);
  20.                 if (node.mark == true) break;
  21.                 if (i == s.length() - 1) {
  22.                     node.mark = true;
  23.                 }
  24.             }
  25.         }
  26.     }
  27.  
  28.     public String replaceWords(List<String> dict, String sentence) {
  29.         Collections.sort(dict);
  30.         Trie root = new Trie();
  31.         for (int i = 0; i < dict.size(); i++) {
  32.             root.insert(dict.get(i));
  33.         }
  34.         StringBuilder ans = new StringBuilder();
  35.         int len = sentence.length();
  36.         int i = 0;
  37.         char ch;
  38.         while (i < len) {
  39.             while (i < len && sentence.charAt(i) == ' ') {
  40.                 ans.append(' ');
  41.                 i++;
  42.             }
  43.             Trie node = root;
  44.             while (i < len && sentence.charAt(i) != ' ') {
  45.                 ch = sentence.charAt(i);
  46.                 if (node == null) {
  47.                     ans.append(ch);
  48.                 } else if (node.mark == true) {
  49.  
  50.                 } else {
  51.                     node = node.children.getOrDefault(ch, null);
  52.                     ans.append(ch);
  53.                 }
  54.                 i++;
  55.             }
  56.         }
  57.         return ans.toString();
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment