zoukankan      html  css  js  c++  java
  • 面试题 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];
        }
    }
  • 相关阅读:
    UGUI优化干货总结
    C#合成解析XML与JSON
    镜头跟随玩家移动
    Unity 5 Skybox 旋转
    多线程实现资源下载
    自定义配置文件的使用及加载-txt
    linux下mysql主从复制搭建
    常用模块-正则re
    Elasticsearch分布式搜索
    redis主从复制原理与优化-高可用
  • 原文地址:https://www.cnblogs.com/yonezu/p/13271946.html
Copyright © 2011-2022 走看看