• 面试题 17.13. 恢复空格


    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];
        }
    }
  • 相关阅读:
    java方法参数传值传引用的一点看法
    Oracle触发器介绍
    CASE WHEN
    group by ,order by ,having
    Java中使用正则表达式
    Oracle 9i 分析函数参考手册
    ORACLE round 与 trunc 的区别
    oracle的默认表名长度(30)
    order by 使用索引的情况
    解析oracle的ROWNUM 作者: chen_liang
  • 原文地址:https://www.cnblogs.com/yonezu/p/13271946.html
Copyright © 2020-2023  润新知