[Leetcode][程序员面试金典][面试题17.13][JAVA][恢复空格][动态规划][Trie][字符串哈希]
【問題描述】[中等]
【解答思路】
1. 動態規劃
動態規劃流程
第 1 步:設計狀態
dp[i] 表示字符串的前 i 個字符的最少未匹配數。
第 2 步:狀態轉移方程
假設當前我們已經考慮完了前 i -1個字符了,對于前 i 個字符對應的最少未匹配數:
第 i 個字符未匹配,則 dp[i] = dp[i+1] + 1,即不匹配數加 1;
遍歷前 i -1個字符,若以其中某一個下標 j 為開頭、以第 i 個字符為結尾的字符串正好在詞典里,則 dp[i] = min(dp[ i ], dp[ j ]) 更新 dp[i]。
第 3 步:考慮初始化
int[] dp = new int[n+1];
dp[0] = 0;
第 4 步:考慮輸出
dp[n];
時間復雜度:O(N^3) 空間復雜度:O(N)
class Solution {public int respace(String[] dictionary, String sentence) {Set<String> dic = new HashSet<>();for(String str: dictionary) dic.add(str);int n = sentence.length();//dp[i]表示sentence前i個字符所得結果int[] dp = new int[n+1];for(int i=1; i<=n; i++){dp[i] = dp[i-1]+1; //先假設當前字符作為單詞不在字典中for(int j=0; j<i; j++){if(dic.contains(sentence.substring(j,i))){dp[i] = Math.min(dp[i], dp[j]);}}}return dp[n];} }2. Trie字典樹優化
復雜度分析
3. 字符串哈希
復雜度分析
【總結】
1.動態規劃流程
第 1 步:設計狀態
第 2 步:狀態轉移方程
第 3 步:考慮初始化
第 4 步:考慮輸出
第 5 步:考慮是否可以狀態壓縮
2. Rabin-Karp 字符串編碼 (字符串哈希)
3.Trie
class Trie {public Trie[] next;public boolean isEnd;public Trie() {next = new Trie[26];isEnd = false;}public void insert(String s) {Trie curPos = this;for (int i = s.length() - 1; i >= 0; --i) {int t = s.charAt(i) - 'a';if (curPos.next[t] == null) {curPos.next[t] = new Trie();}curPos = curPos.next[t];}curPos.isEnd = true;} }轉載鏈接:https://leetcode-cn.com/problems/re-space-lcci/solution/hui-fu-kong-ge-by-leetcode-solution/
Rabin-Karp 字符串編碼 參考鏈接:https://leetcode-cn.com/problems/longest-happy-prefix/solution/zui-chang-kuai-le-qian-zhui-by-leetcode-solution/
總結
以上是生活随笔為你收集整理的[Leetcode][程序员面试金典][面试题17.13][JAVA][恢复空格][动态规划][Trie][字符串哈希]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python航空订票系统_航空订票系统
- 下一篇: 1048 石子归并