【动态规划】LeetCode面试题 17.13.恢复空格

面试题 17.13. 恢复空格

哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。

像句子"I reset the computer. It still didn’t boot!"已经变成了"iresetthecomputeritstilldidntboot"。

在处理标点符号和大小写之前,你得先把它断成词语。当然了,你有一本厚厚的词典dictionary,不过,有些词没在词典里。假设文章用sentence表示,设计一个算法,把文章断开,要求未识别的字符最少,返回未识别的字符数。

注意:本题相对原题稍作改动,只需返回未识别的字符数

示例:

输入:
dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
输出: 7
解释: 断句后为"jess looked just like tim her brother",共7个未识别字符。

提示:

    0 <= len(sentence) <= 1000
    dictionary中总字符数不超过 150000。
    你可以认为dictionary和sentence中只包含小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/re-space-lcci

解题思路:

字符串问题优先考虑动态规划:

设置一个动态转移数组dp[ ]来存储最少未识别字符数,大小等于sentence.size()+1,dp[0]=0。

在遍历sentence的过程中,每遍历一个字符,当前字符对应的dp[ ]也就是dp[i + 1]=dp[ i ] + 1,意思就是假设此时这个字符是翻译过程中多余的。

当已遍历senttence数组的长度开始等于或大于dictionary中某个word的长度时,开始匹配。

我们用如下方式检验以当前字符为尾的一段字符能否与dictionary中的某个word相匹配:

if(word == sentence.substr(i+1-word.size(),word.size()))

若匹配成功:

动态转移方程:dp[i + 1]=min(dp[i+1],dp[i+1-word.size()])

此时的dp[ i + 1]值更新来自与两条途径:

①dp[ i + 1 - word.size()]中存放的是匹配成功时前一个字符对应的最少未识别字符数。

②以 i 结尾往前数的字符串可能有多个,我们要它们之中的最小值,所以需要用到min()来获得当前长度对应最小dp[ ]。

贴上代码:

int respace(vector<string>& dictionary, string sentence) {
    int n = sentence.size();
    vector<int> dp(n + 1);
    for(int i = 0;i < n;i ++){
        dp[i + 1] = dp[i]+ 1;
        for(auto word : dictionary){
            if(word.size() <= i + 1){
                if(word == sentence.substr(i+1-word.size(),word.size()))
                    dp[i + 1]=min(dp[i+1],dp[i+1-word.size()]);
            }
        }
    }
    return dp[n];
}

时间复杂度:O(n^2);空间复杂度:O(n)。

猜你喜欢

转载自blog.csdn.net/cjw838982809/article/details/107702202