class Solution { public int respace(String[] dictionary, String sentence) { int n = sentence.length(); if(n == 0) return 0; Trie t = new Trie(); for(String s : dictionary) { t.insert(s); } char[] arr = sentence.toCharArray(); int[] dp = new int[n+1]; // dp[i] 代表以i为起点,最少的未识别字符数 for(int i = n - 1; i >= 0; i--) { dp[i] = t.getMin(i,arr,dp); } return dp[0]; } } // Trie class Trie { private TrieNode root; public Trie() { root = new TrieNode(' '); } public void insert(String s) { char[] arr = s.toCharArray(); TrieNode node = root; for(int i = 0; i < arr.length; i++) { char c = arr[i]; if(node.sons[c-'a'] == null) node.sons[c-'a'] = new TrieNode(c); node = node.sons[c-'a']; } node.isWord = true; } public int getMin(int i, char[] arr, int[] dp) { int ans = dp[i+1] + 1; // 初始化 TrieNode node = root; for(; i < arr.length; i++) { // 从当前点向前找,看看有多少个从i开始的可识别字符数 dp[i] = dp[i+可识别数] if(node.sons[arr[i] - 'a'] != null) { node = node.sons[arr[i] - 'a']; if(node.isWord) { ans = Math.min(ans,dp[i+1]); } } else { break; } } return ans; } } class TrieNode { TrieNode[] sons; char c; boolean isWord; public TrieNode(char c) { this.c = c; sons = new TrieNode[26]; } }