Open In App
Related Articles

Count the Number of matching characters in a pair of strings

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.
Examples: 

Input: str1 = “abcdef”, str2 = “defghia” 
Output:
Matching characters are: a, d, e, f
Input: str1 = “aabcddekll12”, str2 = “bb22ll@55k” 
Output:
Matching characters are: b, 1, 2, @, k 


Approach: 

  1. Initialize a counter variable with 0. 
  2. Iterate over the first string from the starting character to ending character. 
  3. If the character extracted from the first string is found in the second string, then increment the value of the counter by 1.
  4. The final answer will be count/2 as the duplicates are not being considered.
  5. Output the value of counter


Below is the implementation of the above approach. 
 

C++

// C++ code to count number of matching
// characters in a pair of strings
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the matching characters
void count(string str1, string str2)
{
    int c = 0, j = 0;
 
    // Traverse the string 1 char by char
    for (int i = 0; i < str1.length(); i++) {
 
        // This will check if str1[i]
        // is present in str2 or not
        // str2.find(str1[i]) returns -1 if not found
        // otherwise it returns the starting occurrence
        // index of that character in str2
        if (str2.find(str1[i]) >= 0
            and j == str1.find(str1[i]))
            c += 1;
        j += 1;
    }
    cout << "No. of matching characters are: "
         << c / 2;
}
 
// Driver code
int main()
{
    string str1 = "aabcddekll12@";
    string str2 = "bb2211@55k";
 
    count(str1, str2);
}

                    

Java

// Java code to count number of matching
// characters in a pair of strings
class GFG
{
     
    // Function to count the matching characters
    static void count(String str1, String str2)
    {
        int c = 0, j = 0;
     
        // Traverse the string 1 char by char
        for (int i = 0; i < str1.length(); i++)
        {
     
            // This will check if str1[i]
            // is present in str2 or not
            // str2.find(str1[i]) returns -1 if not found
            // otherwise it returns the starting occurrence
            // index of that character in str2
            if (str2. indexOf(str1.charAt(i)) >= 0)
            {
                c += 1;
        }
    }
        System.out.println("No. of matching characters are: " + c);
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String str1 = "aabcddekll12@";
        String str2 = "bb2211@55k";
     
        count(str1, str2);
    }
}
 
// This code is contributed by AnkitRai01

                    

Python3

# Python3 code to count number of matching
# characters in a pair of strings
 
# Function to count the matching characters
def count(str1, str2) :
 
    c = 0; j = 0;
 
    # Traverse the string 1 char by char
    for i in range(len(str1)) :
 
        # This will check if str1[i]
        # is present in str2 or not
        # str2.find(str1[i]) returns -1 if not found
        # otherwise it returns the starting occurrence
        # index of that character in str2
        if str1[i] in str2 :
            c += 1;
            #print(str1[i])
        j += 1;
     
    print("No. of matching characters are: ", c );
 
 
# Driver code
if __name__ == "__main__" :
    str1 = "aabcddekll12@";
    str2 = "bb2211@55k";
     
    count(str1, str2);
     
# This code is contributed by AnkitRai01

                    

C#

// C# code to count number of matching
// characters in a pair of strings
using System;
 
class GFG
{
     
    // Function to count the matching characters
    static void count(string str1, string str2)
    {
        int c = 0, j = 0;
     
        // Traverse the string 1 char by char
        for (int i = 0; i < str1.Length; i++)
        {
     
            // This will check if str1[i]
            // is present in str2 or not
            // str2.find(str1[i]) returns -1 if not found
            // otherwise it returns the starting occurrence
            // index of that character in str2
            if (str2.IndexOf(str1[i]) >= 0)
            {
                c += 1;
        }
    }
        Console.WriteLine("No. of matching characters are: " + c);
    }
     
    // Driver code
    public static void Main()
    {
        string str1 = "aabcddekll12@";
        string str2 = "bb2211@55k";
     
        count(str1, str2);
    }
}
 
// This code is contributed by AnkitRai01

                    

Javascript

<script>
 
// JavaScript code to count number of matching
// characters in a pair of strings
 
// Function to count the matching characters
function count(str1, str2)
{
    var c = 0;
 
    // Traverse the string 1 char by char
    for (var i = 0; i < str1.length; i++) {
 
        // This will check if str1[i]
        // is present in str2 or not
        // str2.find(str1[i]) returns -1 if not found
        // otherwise it returns the starting occurrence
        // index of that character in str2
        if (str2.includes(str1[i]))
            c += 1;
    }
    document.write( "No. of matching characters are: " +
         + parseInt(c));
}
 
// Driver code
 
var str1 = "aabcddekll12@";
var str2 = "bb2211@55k";
count(str1, str2);
 
 
</script>

                    

Output
No. of matching characters are: 5







Time Complexity: O(m * (n + m)), where m and n are the length of the given strings str1 and str2 respectively.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Efficient Approach:

Implementation:

C++

#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of matching pairs
int countMatchingCharacters(string str1, string str2)
{
    unordered_map<char, int> charCount;
    int count = 0;
 
    // Count characters in str1
    for (char c : str1) {
        charCount++;
    }
 
    // Check for matching characters in str2
    for (char c : str2) {
        if (charCount > 0) {
            count++;
            charCount--;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    string str1 = "abcdef";
    string str2 = "defghia";
 
    // Function call
    cout << countMatchingCharacters(str1, str2);
    return 0;
}

                    

Java

import java.util.HashMap;
import java.util.Map;
 
public class GFG {
    // Function to count the number of matching pairs
    public static int countMatchingCharacters(String str1, String str2) {
        // Create a HashMap to store character frequencies in str1
        Map<Character, Integer> charCount = new HashMap<>();
        int count = 0;
 
        // Count characters in str1
        for (char c : str1.toCharArray()) {
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }
 
        // Check for matching characters in str2
        for (char c : str2.toCharArray()) {
            if (charCount.containsKey(c) && charCount.get(c) > 0) {
                count++;
                charCount.put(c, charCount.get(c) - 1);
            }
        }
 
        return count;
    }
 
    public static void main(String[] args) {
        String str1 = "abcdef";
        String str2 = "defghia";
 
        // Function call
        int matchingPairs = countMatchingCharacters(str1, str2);
        System.out.println("Number of matching pairs: " + matchingPairs);
    }
}

                    

Python3

# Function to count the number of matching characters
def count_matching_characters(str1, str2):
    char_count = {}
    count = 0
 
    # Count characters in str1
    for c in str1:
        if c in char_count:
            char_count += 1
        else:
            char_count = 1
 
    # Check for matching characters in str2
    for c in str2:
        if c in char_count and char_count > 0:
            count += 1
            char_count -= 1
 
    return count
 
# Driver code
if __name__ == "__main__":
    str1 = "abcdef"
    str2 = "defghia"
 
    # Function call
    print(count_matching_characters(str1, str2))

                    

C#

using System;
using System.Collections.Generic;
 
public class GFG
{
    // Function to count number of matching pairs
    public static int CountMatchingCharacters(string str1, string str2)
    {
        Dictionary<char, int> charCount = new Dictionary<char, int>();
        int count = 0;
 
        // Count characters in str1
        foreach (char c in str1)
        {
            if (charCount.ContainsKey(c))
            {
                charCount++;
            }
            else
            {
                charCount = 1;
            }
        }
 
        // Check for matching characters in str2
        foreach (char c in str2)
        {
            if (charCount.ContainsKey(c) && charCount > 0)
            {
                count++;
                charCount--;
            }
        }
 
        return count;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string str1 = "abcdef";
        string str2 = "defghia";
 
        // Function call
        Console.WriteLine(CountMatchingCharacters(str1, str2));
    }
}

                    

Javascript

// Function to count the number of matching pairs
function countMatchingCharacters(str1, str2) {
    // Create an object to count characters in str1
    const charCount = {};
 
    let count = 0;
 
    // Count characters in str1
    for (const c of str1) {
        if (charCount === undefined) {
            charCount = 1;
        } else {
            charCount++;
        }
    }
 
    // Check for matching characters in str2
    for (const c of str2) {
        if (charCount > 0) {
            count++;
            charCount--;
        }
    }
 
    return count;
}
 
// Driver code
function main() {
    const str1 = "abcdef";
    const str2 = "defghia";
 
    // Function call
    console.log(countMatchingCharacters(str1, str2));
}
 
// Run the main function
main();

                    

Output
4







Time Complexity: O(n),where n is the size of the string.
Auxiliary Space: O(K), where K is the number of unique characters in str1.



Last Updated : 16 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads