java 空格变成问号,leetcode面试题 17.13(恢复空格)--Java语言实现

求:

哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"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中只包含小写字母。

解:

1、动态规划

未识别的字符数=所有字符数(字符长长度)-已识别的字符数。

因为每一步的结果与上一步的结果相关,且与之后的结果无关,符合动态规划的典型特征。我们使用一个一维的dp数组保存每一步的结果。

从前往后使用一个变量i顺序遍历字符串,遍历字符串的过程中,dp[i]或者等于dp[i-1],或者因为子串出现了与dictionary中字典的匹配(遍历字符串使用变量j),为dp[i-dictionary[j].length]+dictionary.length。选择这2者中的较大者,作为dp[i]。注意这里为了确保下标有效,需要保证i>=dictionary.length。

时间复杂度:O(M^2*N),其中M是字典字符串数组的长度,N是sentence字符串的长度(substring的复杂度是O(N),外面2层for循环)

空间复杂度:O(N)

public intrespace(String[] dictionary,String sentence) {

intN = sentence.length();intM = dictionary.length;intdp[] = new int[N+1];for(inti=1;i<=N;i++){

dp[i]=dp[i-1];for(intj=0;j

intdicLen = dictionary[j].length();if(i

dp[i] = Math.max(dp[i],dp[i-dicLen]+dicLen);}

}

returnN-dp[N];}

2、动态规划+线段树

这是一个非常适合本题的数据结构。核心思想是将dictionary数组中的字符串,按反向顺序遍历字符,然后加入到线段树中。这样从线段树的根节点遍历树的时候,就相当于与字典做匹配。具体可以参考官方给出的题解。这个方法整体复杂度较高,难度在于对于线段树的插入、遍历需要熟悉,并且需要和动态规划结合。

时间复杂度:O(∣dictionary∣+n

空间复杂度:O(∣dictionary∣∗S+n)

classSolution {

public intrespace(String[] dictionary,String sentence) {

intn = sentence.length();

Trie root = newTrie();for(String word : dictionary) {

root.insert(word);}

int[] dp = new int[n + 1];Arrays.fill(dp,Integer.MAX_VALUE);dp[0] = 0;for(inti = 1;i <= n;++i) {

dp[i] = dp[i - 1] + 1;

Trie curPos = root;for(intj = i;j >= 1;--j) {

intt = sentence.charAt(j - 1) - 'a';if(curPos.next[t] == null) {

break;} else if(curPos.next[t].isEnd) {

dp[i] = Math.min(dp[i],dp[j - 1]);}

if(dp[i] == 0) {

break;}

curPos = curPos.next[t];}

}

returndp[n];}

}

classTrie {

publicTrie[] next;public booleanisEnd;

publicTrie() {

next= newTrie[26];isEnd= false;}

public voidinsert(String s) {

Trie curPos = this;

for(inti = s.length() - 1;i >= 0;--i) {

intt = s.charAt(i) - 'a';if(curPos.next[t] == null) {

curPos.next[t] = newTrie();}

curPos = curPos.next[t];}

curPos.isEnd= true;}

}

3、动态规划+字符串哈希

参考官方题解,与方法2类似,但是能达到更好的空间复杂度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值