题目
给定两个字符串s1,s2,在s2中出现的字符从s1中删除
例如:s1: 'abc'
s2: 'cde'
输出:s1: 'ad'
code1(正则替换)
function deleteCharInS1(s1, s2) {
for (let i = 0; i < s2.length; i++) {
const reg = new RegExp(s2[i], 'g')
// 用正则实现全局替换
if (reg.test(s1)) s1 = s1.replace(reg, '')
}
return s1
}
code2(哈希表查询)
function deleteCharInS1(s1, s2) {
const map = {}
for (let i = 0; i < s2.length; i++) {
if (!map[s2[i]]) {
map[s2[i]]= true
}
}
let newStr = ''
for (let i = 0; i < s1.length; i++) {
if (!map[s1[i]]) {
newStr += s1[i]
}
}
return newStr
}
网友评论