删除 2 个字符串的字符,使它们成为打字稿中的字谜
delete character of 2 string to make them anagram in typescript
我试图解决其中一项 Hackerrank 挑战 String: Making Anagrams
我有 2 个这样的字符串:
let a: string = "fcrxzwscanmligyxyvym"
let b: string = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"
我有一个函数只通过了 3 次测试!!! :
function makeAnagram(a: string, b: string): number {
type Map = {
[key :string] : number
}
let string1 = a.split('')
let string2 = b.split('')
let map : Map = {}
let deletedCount = 0
let firstCount = 0
let isMoreThanTwo = false
for(let i of string1) {
map[i] = (map[i] | 0) + 1
}
for(let i of string2){
map[i] = (map[i] | 0) + 1
}
for(let i in map) {
if(map[i] == 1) {
deletedCount++
firstCount++
} else if(map[i] > 2) {
isMoreThanTwo = true
deletedCount += (map[i] - 1)
}
}
return isMoreThanTwo ? deletedCount + firstCount : deletedCount
有没有其他方法可以统计删除的字符数?你们能给我一些建议吗,谢谢
我刚刚解决了这个问题,但在通过所有测试用例之前,我找到了我使用的解决方案
for (let [k, v] of map) {
remain += v;
}
失败了 13/16
个测试用例,然后我调试了程序,发现有时当我们从这一步的前面减去 1
时,结果是 less than 0
所以哟也必须处理这种情况,我处理为
for (let [k, v] of map) {
remain += v < 0 ? v * -1 : v;
}
Now, all test cases are passed
function makeAnagram(a, b) {
const [small, big] = a.length < b.length ? [a, b] : [b, a];
const map = new Map();
for (let c of small) {
map.set(c, (map.get(c) ?? 0) + 1);
}
let remain = 0;
for (let c of big) {
!map.has(c) ? remain++ : map.set(c, map.get(c) - 1);
}
for (let [k, v] of map) {
remain += v < 0 ? v * -1 : v;
}
return remain;
}
console.log(makeAnagram("fast", "sofasty"));
我试图解决其中一项 Hackerrank 挑战 String: Making Anagrams
我有 2 个这样的字符串:
let a: string = "fcrxzwscanmligyxyvym"
let b: string = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"
我有一个函数只通过了 3 次测试!!! :
function makeAnagram(a: string, b: string): number {
type Map = {
[key :string] : number
}
let string1 = a.split('')
let string2 = b.split('')
let map : Map = {}
let deletedCount = 0
let firstCount = 0
let isMoreThanTwo = false
for(let i of string1) {
map[i] = (map[i] | 0) + 1
}
for(let i of string2){
map[i] = (map[i] | 0) + 1
}
for(let i in map) {
if(map[i] == 1) {
deletedCount++
firstCount++
} else if(map[i] > 2) {
isMoreThanTwo = true
deletedCount += (map[i] - 1)
}
}
return isMoreThanTwo ? deletedCount + firstCount : deletedCount
有没有其他方法可以统计删除的字符数?你们能给我一些建议吗,谢谢
我刚刚解决了这个问题,但在通过所有测试用例之前,我找到了我使用的解决方案
for (let [k, v] of map) {
remain += v;
}
失败了 13/16
个测试用例,然后我调试了程序,发现有时当我们从这一步的前面减去 1
时,结果是 less than 0
所以哟也必须处理这种情况,我处理为
for (let [k, v] of map) {
remain += v < 0 ? v * -1 : v;
}
Now, all test cases are passed
function makeAnagram(a, b) {
const [small, big] = a.length < b.length ? [a, b] : [b, a];
const map = new Map();
for (let c of small) {
map.set(c, (map.get(c) ?? 0) + 1);
}
let remain = 0;
for (let c of big) {
!map.has(c) ? remain++ : map.set(c, map.get(c) - 1);
}
for (let [k, v] of map) {
remain += v < 0 ? v * -1 : v;
}
return remain;
}
console.log(makeAnagram("fast", "sofasty"));