'How to identify the number of common character between two strings?

Given 2 strings, str1 and str2, as input, return the count of the chars which are in the same position in str1 and str2.

Sample Input #1

count("New York","New Delhi")

Sample Output #1

4

Because the two strings share the same four leading characters: "New "

Sample Input #2

count("rhinoceroses","hippopotamus")

Sample Output #2

2

Because 'o' occupies the fourth position and 's' the eleventh position in both strings.

MyApproach

@Edit

public int count(String str1, String str2)
{
    int p=0;
    int k=0;
    int count=0;
    int l1=str1.length();
    int l2=str2.length();
    if(l1>=l2)
    {
     while(k<l2)
     {
         char ch1=str1.charAt(p);
         char ch2=str2.charAt(k);
    
            if(ch1==ch2)
            {
                p++;
                k++;
                count++;
            }
            else
            {
                p++;
                k++;
                
            }
      }         
     }
     else
     {
         char ch1=str1.charAt(p);
         char ch2=str2.charAt(k);
    
         while(k<l1)
         {
             
            if(ch1==ch2)
            {
                p++;
                k++;
                count++;
            }
            else
            {
                p++;
                k++;
                
            }
          }         
      }
   return count;
}   

Parameters Actual Output Expected Output

'Trisect''Classes' 0 1

I am getting correct output now.

Thanku



Solution 1:[1]

This can be done more preciously using a single loop. Find the below code with the solution :-

class GetCount {

public static void main(String args[]) {
    String myString = "rhinoceroses";
    String myString1 = "hippopotamus";

    count(myString, myString1);
}

/**
 * @param myString
 * @param myString1
 */
private static void count(String myString, String myString1) {
    int i = 0;
    int count = 0;
    int length = myString.length() < myString1.length() ? myString.length() : myString1.length();
    while(i < length) {
        if(myString.charAt(i) == myString1.charAt(i)) {
            count++;
        }
        i++;
    }
    System.out.println("Count is :: " + count);

}

}

Solution 2:[2]

Here is a compact solution, very easy to understand.


Solution

public static int count(String s1, String s2){
    int count = 0;
    for (int i = 0 ; i < (s1.length() > s2.length() ? s2 : s1).length() ; i++){
        count += s1.charAt(i) == s2.charAt(i) ? 1 : 0;
    }
    return count;
}

Input

public static void main(String[] args) {
    System.out.println(
            "New York, New Delhi : " 
            + count("New York", "New Delhi"));

    System.out.println(
            "Rhinoceroses, Hippopotamus : " 
            + count ("Rhinoceroses", "Hippopotamus"));
}

Output

New York, New Delhi : 4
Rhinoceroses, Hippopotamus : 2

Solution 3:[3]

The solutions provided before are useless, as they work only if the characters are in the same sequence. Here is my solution:

private int commonCharacterCount(String s1, String s2) {
    int counter = 0;

    List<Character> list = new LinkedList<>();
    for (char aChar : s1.toCharArray()) {
        list.add(aChar);
    }

    for (char c : s2.toCharArray()) {
        if (list.contains(c)) {
            list.remove(Character.valueOf(c));
            counter++;
        }
    }
    return counter;
}

You are welcome :)

Solution 4:[4]

You can also do something like this. (Try it) -

public int count(String s1, String s2) {
    int result=0;
    char[] ch1=s1.toCharArray();
    char[] ch2=s2.toCharArray();

    if(ch1.length>ch2.length){
    for(int i=0;i<ch2.length;i++){
        if(ch1[i]==ch2[i]){
            result++;
        }
    }
    }
    else{
        for(int i=0;i<ch1.length;i++){
            if(ch2[i]==ch1[i]){
                result++;
            }
        }
    }
    return result;
}

Solution 5:[5]

Typescript solution. Guaranteed constraints: 1 ? s1.length ? 15, 1 ? s2.length ? 15

function commonCharacterCount(s1: string, s2: string): number {
    let count = 0;
    let s_1 = s1.split("");
    let s_2 = s2.split("");

    for (let i = 0; i < s_1.length; i++) {
        for (let j = 0; j < s_2.length; j++) {
            if (s_1[i] == s_2[j]) {
                count++;
                s_2.splice(j, 1);
                break;
            }
        }
    }
    return(count);
}

Solution 6:[6]

Since you need to count of the chars which are in the same position we can do it in a single loop checking at each iteration (string position) if the chars are equal or not. And the number of iteration should be the minimum length of str1 and str2 (maybe we could extract Math.min(str1.length(), str2.length()) in a variable). I compressed the if - else branches from your solution to a single loop using the minimum string length in loop condition.

public int countCommonChars(String str1, String str2) {
  int commonCharsNumber = 0;
  for(int i=0; i< Math.min(str1.length(), str2.length()); i++) {
    if (str1.charAt(i) == str2.charAt(i)) {
      commonCharsNumber++;
    }
  }
  return commonCharsNumber;
}

Solution 7:[7]

int commonCharacterCount(String s1, String s2) {

    Map<String, Integer> mapOfString1 = getOcuurances(s1);
    Map<String, Integer> mapOfString2 = getOcuurances(s2);

    int counter = 0;

    for (Map.Entry<String, Integer> entry : mapOfString2.entrySet()) {
        if (mapOfString1.get(entry.getKey()) != null) {
            if (mapOfString1.get(entry.getKey()) > entry.getValue()) {
                counter += entry.getValue();
            } else {
                counter += mapOfString1.get(entry.getKey());
            }
        }

    }
    return counter;
}

public Map<String, Integer> getOcuurances(String s) {
    Map<String, Integer> hashMap = new HashMap<>();
    String[] strings = s.split("");
    for (int i = 0; i < strings.length; i++) {
        if (hashMap.containsKey(strings[i])) {
            hashMap.put(strings[i], hashMap.get(strings[i]) + 1);
        } else {
            hashMap.put(strings[i], 1);
        }
    }
    return hashMap;
}

Solution 8:[8]

int count(String s1, String s2) {
    Map<Character, Integer> charCountMap1 = getCharacterCount(s1);
    Map<Character, Integer> charCountMap2 = getCharacterCount(s2);

    return charCountMap1.entrySet().stream().map(charCountEntry ->
        Math.min(charCountEntry.getValue(), charCountMap2.getOrDefault(charCountEntry.getKey(), 0))
    ).collect(Collectors.summingInt(value -> value));
}

private Map<Character, Integer> getCharacterCount(String str) {
    Map<Character, Integer> charCountMap = new HashMap<>();
    for (int i = 0; i < str.toCharArray().length; i++) {
        Integer count = charCountMap.getOrDefault(str.charAt(i), 0);
        charCountMap.put(str.charAt(i), ++count);
    }
    return charCountMap;
}

Solution 9:[9]

I would like to go with below:-

    private static int solution(String s1, String s2) {

    int count = 0;

    List<Character> listChars = s1.chars().mapToObj(chr -> (char) chr)
            .collect(Collectors.toCollection(LinkedList::new));

    for (char c : s2.toCharArray()) {
        if (listChars.contains(c)) {
            listChars.remove(Character.valueOf(c));
            count++;
        }
    }
    return count;
}

Solution 10:[10]

Though there is already an accepted answer but I don't feel that answer is concise enough, hence I am giving mine (haven't compiled, treat it as psuedo-code please)

public static int count(String s1, String s2) {
    if (s1 == null || s2==null ||s1.isEmpty() || s2.isEmpty()) {
        return 0;
    }
    int minLength = Math.min(s1.length(), s2.length());
    int count = 0;
    for (int i < 0; i < minLength; ++i) {
        if (s1.charAt(i) == s2.charAt(i)) {
            ++count;
        }
    }
    return count;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ashisahu
Solution 2 Yassin Hajaj
Solution 3 GuessWho
Solution 4 Aritro Sen
Solution 5 Kyle Henry
Solution 6
Solution 7 Shaaban Ebrahim
Solution 8 Naseer Ullah
Solution 9 Neeraj Sharma
Solution 10