1.URL化
编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
示例2:
输入:" ", 5
输出:"%20%20%20%20%20"
提示:
字符串长度在[0, 500000]范围内。
IPO过程:
I:输入一个将要被url化的字符串和一个表示字符真实长度的length
P:要将空格转化为%20
(1)将字符串转为数组
(2)对数组进行处理,由示例1我们可以看出,字符串最后的空格是被当成一个空格来计算,因此我们可以直接根据长度切片
(3)遍历数组,将数组转化为“%20”
O:输出一个将空格转为%20的字符串
/**
* @param {string} S
* @param {number} length
* @return {string}
*/
var replaceSpaces = function(S, length) {
//先转化为数组
//由于字符串的尾部多个空格会被当成一个,因此,通过length长度进行切片
var arr=S.split('').slice(0,length)
//对数组做循环
for(var i=0;i<arr.length;i++){
if(arr[i]==' '){
arr[i]='%20'
}
}
//最后在拼接为字符串
return arr.join('')
};
const respace = (dictionary, sentence) => {
const len = sentence.length;
const dp = new Array(len + 1);
dp[0] = 0;
for (let i = 1; i <= len; i++) {
dp[i] = dp[i - 1] + 1;
for (const word of dictionary) { // 遍历字典里的单词
if (sentence.substring(i - word.length, i) == word) { // 截取字典词的长度与字典词比较
dp[i] = Math.min(dp[i], dp[i - word.length]);
}
}
}
return dp[len];
};
2.恢复空格
哦,不!你不小心把一个长篇文章中的空格、标点都删掉了,并且大写也弄成了小写。像句子"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中只包含小写字母。
DP思路
思路和 word break 那道题很像,拥有前 i 个字符的子串 [0,i-1] 的最优解 取决于两部分:
拥有前 j 个字符的子串 [0,j-1] —— 规模更小的子问题
[j,i-1] 是否是字典里的单个单词
即,我们用指针 j 去划分,[j,i-1] 区间从长度 0 逐渐到 i,考察它是否是字典的单词
作者:hyj8
链接:https://leetcode-cn.com/problems/re-space-lcci/solution/shou-hua-tu-jie-dp-si-lu-by-hyj8-2/
const respace = (dictionary, sentence) => {
const len = sentence.length;
const dp = new Array(len + 1);
const wordDict = new Set();
for (const word of dictionary) {
wordDict.add(word);
}
dp[0] = 0; // 前0个字符 没有字符 更没有未识别的字符
for (let i = 1; i <= len; i++) {
dp[i] = dp[i - 1] + 1; // 前i个字符的最少未识别的字符 保底的情况(可能还可以更少)
for (let j = i - 1; j >= 0; j--) { // j 从 i-1开始 word的长度从0开始
const word = sentence.substring(j, i);
if (wordDict.has(word)) {
dp[i] = Math.min(dp[i], dp[j]);
} else {
dp[i] = Math.min(dp[i], dp[j] + i - j);
}
}
}
return dp[len];
};
优化, 学习别人的解法
[0,i-1] 区间的末尾逐个截取字典每个单词的长度,看看截出来的是否是字典单词,如果是,则 dp[i] = Math.min(dp[i], dp[i - word.length])
const respace = (dictionary, sentence) => {
const len = sentence.length;
const dp = new Array(len + 1);
dp[0] = 0;
for (let i = 1; i <= len; i++) {
dp[i] = dp[i - 1] + 1;
for (const word of dictionary) { // 遍历字典里的单词
if (sentence.substring(i - word.length, i) == word) { // 截取字典词的长度与字典词比较
dp[i] = Math.min(dp[i], dp[i - word.length]);
}
}
}
return dp[len];
};