面試題 17.13. 恢復空格
阿新 • • 發佈:2020-07-09
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 voidinsert(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]; } }