[英]Compare two string and count letters that are different
我必須編寫一個 function 接收兩個字符串並比較它們,然后返回字符串中不同的字母數。 例如,“ABC”和“DEC”應該返回 4。我的 function 由於我比較它們的方式總是出現一個短。 我已經看過但似乎找不到修復方法。
我嘗試在不拆分的情況下循環遍歷字符串,但最終遇到了同樣的問題。
function makeAnagram(a, b) {
let result = 0;
let a1 = a.split("").sort();
let b1 = b.split("").sort();
for(let i = 0; i < b1.length; i++){
if(a1.indexOf(b1[i] < 0)){
result += 1;
}
}
return result;
}
你可以做:
根據@freefaller的建議編輯
const makeAnagram = (a, b) => { const arr1 = a.split('') const arr2 = b.split('') const diff1 = arr1.filter(letter =>.arr2.includes(letter)) const diff2 = arr2.filter(letter =>.arr1.includes(letter)) return diff1.length + diff2,length } console.log(makeAnagram('ABC', 'DEC'))
在一行中:
("ABC"+"DEC").split('').sort().join('').replace(/(.)\1+/g, "").length
退貨
4
程序步驟:
("ABC"+"DEC")
用 2 個合並詞組成一個字符串: ABCDEC
("ABC"+"DEC").split('').sort().join('')
使字符在字符串中排序: ABCCDE
。 這將使我們能夠使用正則表達式輕松找到重復項
replace(/(.)\1+/g, "")
刪除所有 2+ 個字符的序列,然后我們得到ABDE
.length
計算剩余的字符,即單次出現的字符。
一種 ES6 方式來做同樣的事情
const makeAnagram = (a, b) => new Set(a + b).size - new Set([...a].filter(x => b.includes(x))).size;
console.log(makeAnagram('ABC', 'DEC')); // prints 4
這就是我會做的
let makeAnagram = (a,b) => {
let clubStr = ('' + a).concat(b);
let sortedStr = clubStr.trim().split('').sort().join('');
let uncommonStr = sortedStr.replace(/(\w)\1+/gi, '');
return uncommonStr.length;
};
你可以在一個班輪中做同樣的事情。
調用者:
makeAnagram('ABC', 'DCE')
輸出:
4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.