算法题 |
算法刷题专栏 | 面试必备算法 | 面试高频算法
越难的东西,越要努力坚持,因为它具有很高的价值,算法就是这样✨
作者简介:硕风和炜,CSDN-Java领域新星创作者,保研|国家奖学金|高中学习JAVA|大学完善JAVA开发技术栈|面试刷题|面经八股文|经验分享|好用的网站工具分享
恭喜你发现一枚宝藏博主,赶快收入囊中吧
人生如棋,我愿为卒,行动虽慢,可谁曾见我后退一步?
算法题 |
在开始下面这道面试题目的时候,我们可以先看一下我之前和该题目具有相同求解思路的一道题目,学习完该题目再看这道题目就会非常简单了。
博客地址:【LeetCode: 139. 单词拆分 | 暴力递归=>记忆化搜索=>动态规划】
哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"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中只包含小写字母。
class Solution {
public int respace(String[] dictionary, String sentence) {
return process(0,sentence,dictionary);
}
public int process(int index,String s,String[] dictionary){
if(index>=s.length()) return 0;
int ans=Integer.MAX_VALUE;
for(int i=0;i<dictionary.length;i++){
String dict=dictionary[i];
if(s.startsWith(dict,index)){
ans=Math.min(ans,process(index+dict.length(),s,dictionary));
}
}
ans=Math.min(ans,process(index+1,s,dictionary)+1);
return ans;
}
}
class Solution {
int[] dp;
public int respace(String[] dictionary, String sentence) {
dp=new int[sentence.length()];
Arrays.fill(dp,-1);
return process(0,sentence,dictionary);
}
public int process(int index,String s,String[] dictionary){
if(index>=s.length()) return 0;
if(dp[index]!=-1) return dp[index];
int ans=Integer.MAX_VALUE;
for(int i=0;i<dictionary.length;i++){
String dict=dictionary[i];
if(s.startsWith(dict,index)){
ans=Math.min(ans,process(index+dict.length(),s,dictionary));
}
}
ans=Math.min(ans,process(index+1,s,dictionary)+1);
return dp[index]=ans;
}
}
class Solution {
public int respace(String[] dictionary, String s) {
int[] dp=new int[s.length()+1];
for(int index=s.length()-1;index>=0;index--){
int ans=Integer.MAX_VALUE;
for(int i=0;i<dictionary.length;i++){
String dict=dictionary[i];
if(s.startsWith(dict,index)){
ans=Math.min(ans,dp[index+dict.length()]);
}
}
ans=Math.min(ans,dp[index+1]+1);
dp[index]=ans;
}
return dp[0];
}
}
最后,我想送给大家一句一直激励我的座右铭,希望可以与大家共勉!