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];
        }
    }
  • 相关阅读:
    学习进度条第十周
    学习进度条第九周
    结巴分词python
    竞品分析
    学期总结(一)------文献挖掘
    分类结果评估
    scrapy 爬虫怎么写入日志和保存信息
    Python 安装 imread报错
    Python爬虫爬中文却显示Unicode,怎样显示中文--问题解答
    Python网络数据采集二
  • 原文地址:https://www.cnblogs.com/yonezu/p/13271946.html
Copyright © 2011-2022 走看看