简体   繁体   English

比较两个字符串并计算不同的字母

[英]Compare two string and count letters that are different

I have to write a function that takes in two strings and compares them then returns the number of letters in the strings that are different.我必须编写一个 function 接收两个字符串并比较它们,然后返回字符串中不同的字母数。 For example "ABC" and "DEC" should return 4. My function always turns up one short because of how I am comparing them.例如,“ABC”和“DEC”应该返回 4。我的 function 由于我比较它们的方式总是出现一个短。 I've looked but can't seem to find a fix.我已经看过但似乎找不到修复方法。

I have tried looping through the string without splitting and ended up with the same problem.我尝试在不拆分的情况下循环遍历字符串,但最终遇到了同样的问题。

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;
 }

You can do:你可以做:

Edited as suggestion by @freefaller根据@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'))

In one line:在一行中:

("ABC"+"DEC").split('').sort().join('').replace(/(.)\1+/g, "").length

Returns退货

4

Steps of the program:程序步骤:

  1. ("ABC"+"DEC") makes a string with the 2 merged words: ABCDEC ("ABC"+"DEC")用 2 个合并词组成一个字符串: ABCDEC

  2. ("ABC"+"DEC").split('').sort().join('') makes the characters sorted in the string: ABCCDE . ("ABC"+"DEC").split('').sort().join('')使字符在字符串中排序: ABCCDE This will enable us to find duplicates easily with regex这将使我们能够使用正则表达式轻松找到重复项

  3. replace(/(.)\1+/g, "") removes all sequences of 2+ characters, then we get ABDE replace(/(.)\1+/g, "")删除所有 2+ 个字符的序列,然后我们得到ABDE

  4. .length counts the remaining characters, which are the ones with single occurence. .length计算剩余的字符,即单次出现的字符。

An ES6 way to do the same一种 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

This is what I would do这就是我会做的

Implementation执行

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;
};

You can do same in one liner .你可以在一个班轮中做同样的事情

Caller: makeAnagram('ABC', 'DCE')调用者: makeAnagram('ABC', 'DCE')

Ouput: 4输出: 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM