最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to count common characters in two strings in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.

Input: s1 = 'abcd', s2 = 'aad'
Output: 2

Input: s1 = 'geeksforgeeks', s2 = 'platformforgeeks'
Output: 8

I tried to like this:

function getSameCount(str, str2) {
  var o = {},
    o2 = {};
  for (var i = 0; i < str.length - 1; i++) {
    if (str[i] in o) {
      o[str[i]] = parseInt(o[str[i]] + 1)
    } else {
      o[str[i]] = 0
    }
  }
  console.log(o);

  for (var i = 0; i < str2.length - 1; i++) {
    if (str[i] in o2) {
      o2[str[i]] = parseInt(o2[str[i]] + 1)
    } else {
      o2[str[i]] = 0
    }
  }

  console.log(o2);
}

getSameCount('abcd', 'aad')

Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.

Input: s1 = 'abcd', s2 = 'aad'
Output: 2

Input: s1 = 'geeksforgeeks', s2 = 'platformforgeeks'
Output: 8

I tried to like this:

function getSameCount(str, str2) {
  var o = {},
    o2 = {};
  for (var i = 0; i < str.length - 1; i++) {
    if (str[i] in o) {
      o[str[i]] = parseInt(o[str[i]] + 1)
    } else {
      o[str[i]] = 0
    }
  }
  console.log(o);

  for (var i = 0; i < str2.length - 1; i++) {
    if (str[i] in o2) {
      o2[str[i]] = parseInt(o2[str[i]] + 1)
    } else {
      o2[str[i]] = 0
    }
  }

  console.log(o2);
}

getSameCount('abcd', 'aad')

Share Improve this question edited Mar 8, 2021 at 12:10 Penny Liu 17.4k5 gold badges86 silver badges108 bronze badges asked Mar 26, 2019 at 5:57 user944513user944513 12.7k51 gold badges185 silver badges346 bronze badges 6
  • And what was the outcome? – GolezTrol Commented Mar 26, 2019 at 5:59
  • Do you need cross browser support? – Leon Commented Mar 26, 2019 at 6:05
  • No but I am not thinking to use inbuild function like include – user944513 Commented Mar 26, 2019 at 6:06
  • @GolezTrol already mentioned – user944513 Commented Mar 26, 2019 at 6:06
  • @user944513, Golez asked what the outcome of your code was – Harshith Rai Commented Mar 26, 2019 at 6:10
 |  Show 1 more comment

8 Answers 8

Reset to default 4

Use for..in loop and includes method

var s1 = "abcd";
var s2 = "aad";

function match(s1, s2) {
    var count = 0;

    for(let i in s1) {
        s2.includes(s1[i]) ? count++ : false;
    }

    return count;
}

console.log(match(s1,s2));

We can convert the second input string to an array, then the next step is to iterate over the first input string and find a match in the second input string's character array.

If a match is found, increment the counter and remove that character from the second input string's character array so that it is not considered in the next match:

//Solution:
function getSameCount(str1, str2) {
  let count = 0;
  const obj = str2.split("");
  for(str of str1){
    let idx = obj.findIndex(s => s === str);
    if(idx >= 0){
      count++;
      obj.splice(idx, 1);
    }
  }
  return count;
}

//Test:
console.log(getSameCount("abcd", "aad"));
console.log(getSameCount("geeksforgeeks", "platformforgeeks"));
console.log(getSameCount("aad", "abcd"));
console.log(getSameCount("platformforgeeks", "geeksforgeeks"));

You can create a custom method on the array and find the number of characters which are common in all the words. Below steps are list of procedure to find the common characters in all the string

  1. Create a prototype method on Array , findCommonWord in this case.

  2. This method accepts an array of string, so input will be like

    [ "abcd", "aad","geeksforgeeksda","platdformforgeeks"].findCommonWord()

  3. First step is to modify the input, to remove duplicate characters from a string using Set then sort it by ascending order of the length of string. This is because number of loop will be least if we have to find common character , that also have to present in string with least length.

  4. Then create a new array with out the first string and split the first string. split will create a new array and iterate over it and check if this character is present in rest of the string.

var s1 = "abcd",
  s2 = "aad",
  s3 = "geeksforgeeksda",
  s4 = "platdformforgeeks";

Array.prototype.findCommonWord = function() {
  let tempArray = this.map(function(item) {
    return [...new Set(item.split(''))].join('');
  }).sort(function(a, b) {
    return a.length - b.length
  })

  let count = 0;
  let firstElm = tempArray[0].split('');
  let restElem = tempArray.splice(1);
  let countObject = {}

  for (let i = 0; i < firstElm.length; i++) {
    let z = findIfIncludes(restElem, firstElm[i]);
    if (z.length === restElem.length) {
      countObject[firstElm[i]] = 1;
    } else {
      countObject[firstElm[i]] = 0
    }
  }

  function findIfIncludes(arr, char) {
    return arr.filter(item => item.includes(char))
  }
  console.log(countObject)
  let totalCount = 0;
  for (let keys in countObject) {
    if (countObject[keys] > 0) {
      totalCount += 1;
    }
  }
  return totalCount;
};
console.log([s1, s2, s3, s4].findCommonWord());

function numberOfSameChars(s1, s2) {
    let obj = {};
    let counter = 0;
    for (let i=0; i<s1.length; i++){
        if(s1[i] in obj) {
            obj[s1[i]]++;
        } else {
            obj[s1[i]] = 1;
        }
    }
    for (let i=0; i<s2.length; i++) {
        if(s2[i] in obj && obj[s2[i]] > 0) {
            obj[s2[i]]--;
            counter++;          
        }
    }
    return counter;
}

Try this code:

function countMatch(s1,s2){
    var count = 0;
    while(s1.length && s2.length){
        if(s2.includes(s1.charAt(0))){
            count++;
            s2 = s2.replace(s1.charAt(0),"");
            s1 = s1.slice(1);
        }
        else {
            s1 = s1.slice(1);
        }
    }
    return count;
}

console.log(countMatch("abcd","aad"));
//2

I used objects to do this, and I was kind of curious about there being another way, as I wanted to take an algorithmic approach as well, but whatever works works.

Anyways, here's the code:

function commonCharacterCount(s1, s2) {
  let string1Counter = {};
  let string2Counter = {};
  let commonCount = 0;
  for(let i = 0; i < s1.length; i++){
      if(!string1Counter.hasOwnProperty(s1[i])){
        string1Counter[s1[i]] = 0; 
      }
      string1Counter[s1[i]]++;
  }
  for(let i = 0; i < s2.length; i++){
      if(!string2Counter.hasOwnProperty(s2[i])){
        string2Counter[s2[i]] = 0; 
      }
      string2Counter[s2[i]]++;
  }
  for(let key in string1Counter){
     if(string2Counter.hasOwnProperty(key)){
       if(string1Counter[key] < string2Counter[key]){
           commonCount += string1Counter[key];
       }
       else{
           commonCount += string2Counter[key];
       }
     }
  }
  return commonCount;
}

The logic is basically to just save all of the characters of each string and their count,check for similarities, and compare the count of common characters. Whichever has the fewer amount of common characters will be the amount shared by both.

O(3N) time complexity, O(2N) space complexity (because of the stored objects). I guess I can also do "delete object" but seems redundant on just an algorithm IDE because it's not like it's running on a server for any extended period of time.

function commonSameCount(s1, s2) {
    var s1Array = s1.split("");
    var s2Array = s2.split("");
    var count = 0;
    let index = 0;
    
    s1Array.filter(s1 => {
        index = s2Array.findIndex(s2 => s2 == s1);
        if(index >= 0){
            count++;
            s2Array.splice(index, 1);
        }
    });
    return count;
}

A simple solution using Regex:

index.js

function getSameCount(s1,s2) {

  for (let i in s2) {
    s1 = s1.replace(s2[i], "1")
  }
  const result = s1.replace(/[^1]/g, '').length

  return result
}
发布评论

评论列表(0)

  1. 暂无评论