Most similar string

Given a string str and an array of strings arr[] of size N, the task is to print a string from arr[], which has maximum count of matching characters with str.

Examples:

Input: str = “vikas”, N = 3, arr[] = [“preeti”, “khusbu”, “katherina”] 
Output: “katherina” 
Explanation: 
Number of similar characters between Str and each string in D[ ] are,  
“preeti” = 1 
“khusbu” = 2 
“katherina” = 3 
Hence, “katherina” has maximum matching characters.

Input: str = “gfg”, N = 3, arr[] = [“goal”, “fog”, “abc”] 
Output: “fog” 
Explanation:
Number of similar characters between Str and each string in D[ ] are,  
“goal” = 1 
“fog” = 2 
“abc” = 0 
Hence, “fog” has maximum matching characters.

Approach: The idea is to consider each string of array arr[], and compare each of its character with the given string str. Keep track of the maximum number of matching characters and corresponding string. Also, make sure to remove the duplicates from each string. Below are the steps:



  1. Create a variable maxVal and a variable val, to keep track of maximum number of matching characters and corresponding string respectively.
  2. Traverse the array arr[] and remove duplicates from each string. Also, remove duplicates from Str.
  3. For each string of arr[], compare it with the given string str, and count the number of matching characters.
  4. Keep updating maxVal with the maximum number of matching characters and val with corresponding string.
  5. Finally, print the value of val after the above operations.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above appraoch
import java.util.*;
import java.io.*;
  
public class GFG {
  
    // Function that print string which
    // has maximum similar characters
    private static void
    maxMatchingChar(ArrayList<String> list,
                    int n, char ch[])
    {
  
        String val = "";
  
        int maxVal = Integer.MIN_VALUE;
  
        for (String s : list) {
  
            // Count matching characters
            int matchingchar = matchingChar(
                s.toLowerCase(), ch);
  
            // Update maxVal if needed
            if (matchingchar > maxVal) {
                maxVal = matchingchar;
                val = s;
            }
        }
  
        System.out.print(val + " ");
    }
  
    // Function that returns the count
    // of number of matching characters
    private static int matchingChar(
        String s, char[] ch)
    {
  
        int freq = 0, c = ch.length;
  
        // Traverse the character array
        for (int i = 0; i < c; i++) {
  
            // If character matches
            // then increment the count
            if (s.contains(
                    String.valueOf(ch[i]))) {
                freq++;
            }
        }
  
        return freq;
    }
  
    // Function to remove duplicate
    // characters
    private static char[] removeDuplicate(String str)
    {
        // To keep unique character only
        HashSet<Character> set
            = new HashSet<Character>();
  
        int c = str.length();
  
        // Inserting character in hashset
        for (int i = 0; i < c; i++) {
  
            set.add(str.charAt(i));
        }
  
        char arr[] = new char[set.size()];
        int index = 0;
  
        // Update string with unique characters
        for (char s : set) {
  
            arr[index] = s;
            index++;
        }
  
        // Return the char array
        return arr;
    }
  
    // Driver Code
    public static void main(
        String[] args) throws Exception
    {
        int n = 3;
        String str = "Vikas";
        String D[] = { "preeti", "khusbu", "katherina" };
  
        // Removing duplicate and
        // convert to lowercase
        char ch[]
            = removeDuplicate(str.toLowerCase());
  
        ArrayList<String> list
            = new ArrayList<String>();
  
        // Insert each string in the list
        for (int i = 0; i < n; i++) {
  
            list.add(D[i]);
        }
  
        // Function Call
        maxMatchingChar(list, n, ch);
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above appraoch
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function that print string which
// has maximum similar characters
private static void maxMatchingChar(List<String> list,
                                    int n, char []ch)
{
    String val = "";
  
    int maxVal = int.MinValue;
  
    foreach(String s in list) 
    {
  
        // Count matching characters
        int matchingchar = matchingChar(
                           s.ToLower(), ch);
  
        // Update maxVal if needed
        if (matchingchar > maxVal)
        {
            maxVal = matchingchar;
            val = s;
        }
    }
    Console.Write(val + " ");
}
  
// Function that returns the count
// of number of matching characters
private static int matchingChar(String s, char[] ch)
{
    int freq = 0, c = ch.Length;
  
    // Traverse the character array
    for(int i = 0; i < c; i++)
    {
  
        // If character matches
        // then increment the count
        if (s.Contains(String.Join("", ch[i])))
        {
            freq++;
        }
    }
    return freq;
}
  
// Function to remove duplicate
// characters
private static char[] removeDuplicate(String str)
{
      
    // To keep unique character only
    HashSet<char> set = new HashSet<char>();
  
    int c = str.Length;
  
    // Inserting character in hashset
    for(int i = 0; i < c; i++)
    {
        set.Add(str[i]);
    }
  
    char []arr = new char[set.Count];
    int index = 0;
  
    // Update string with unique characters
    foreach(char s in set
    {
        arr[index] = s;
        index++;
    }
  
    // Return the char array
    return arr;
}
  
// Driver Code
public static void Main(String[] args) 
{
    int n = 3;
    String str = "Vikas";
    String []D = { "preeti", "khusbu"
                   "katherina" };
  
    // Removing duplicate and
    // convert to lowercase
    char []ch = removeDuplicate(str.ToLower());
  
    List<String> list = new List<String>();
  
    // Insert each string in the list
    for(int i = 0; i < n; i++)
    {
        list.Add(D[i]);
    }
  
    // Function call
    maxMatchingChar(list, n, ch);
}
}
  
// This code is contributed by Rohit_ranjan 

chevron_right


Output: 

katherina

Time Complexity: O(N*M) where M is the maximum length of a string.
Auxiliary space: O(M)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rohit_ranjan

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.