Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count common characters in two strings in JavaScript?

Tags:

javascript

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')
like image 746
user944513 Avatar asked Mar 26 '19 05:03

user944513


3 Answers

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));
like image 92
ellipsis Avatar answered Oct 24 '22 06:10

ellipsis


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"));
like image 22
Fullstack Guy Avatar answered Oct 24 '22 06:10

Fullstack Guy


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;
}
like image 1
Begum Avatar answered Oct 24 '22 07:10

Begum