Number of Common Letters in Two Strings

How to count common characters in two strings in JavaScript?

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"));

How can we return the number of common characters in two strings in R?

inner_join(as.data.frame(table(strsplit(s1, "") )),
as.data.frame(table(strsplit(s2, "") )),
by = "Var1") %>%
mutate(Freq.diff = pmin(Freq.x, Freq.y)) %>%
pull(Freq.diff) %>%
sum()

Or with just base R:

df <- merge(as.data.frame(table(strsplit(s1, ""))),
as.data.frame(table(strsplit(s2, ""))),
by = 1)

sum(pmin(df$Freq.x, df$Freq.y))

Count Common Characters in Strings Python

If you want to maintain a count of the number of characters in common, you should use collections.Counter instead of set.

from collections import Counter

s2 = 'qsrqq'
s1 = 'qqtrr'

common_letters = Counter(s1) & Counter(s2) # => {'q': 2, 'r': 1}
print(sum(common_letters.values())) # => 3

Getting the common character count between two strings

You could go for maps. It may not be the best solution in terms of performance, but imo one that is intuitive to understand. First, iterate each string and collect each of its (distinct) characters with their appearance count. Then, compare the keysets of both maps (i.e. the characters) and for each character you find in both maps, store it together with its minimum appearance count from both maps. So something like this:

// first collect characters with their appearance count in maps:
"aabcc" -> 2xa, 1xb, 2xc
"adcaa" -> 3xa, 1xc, 1xd

// now, get all shared characters with their minimum count from both maps:
a -> min(2,3) = 2
b -> not shared
c -> min(2,1) = 1
d -> not shared

I guess this could be implemented in a cool way using the Stream API, but it would be quite a complex statement, not sure whether you have experience with Streams.

edit: Here's one solution using Streams. I bet there are better ones, both performance-wise and from its approach, but it's the first thing that I tried:

public static void main(String[] args) {
System.out.println(commonCharacterCount("aabcc","adcaa"));
}

public static int commonCharacterCount(String s1, String s2) {
Map<Character, Integer> s1CharacterCount = getCharacterCount(s1);
Map<Character, Integer> s2CharacterCount = getCharacterCount(s2);
return s1CharacterCount.keySet().stream()
.filter(s2CharacterCount.keySet()::contains)
.mapToInt(c -> Math.min(s1CharacterCount.get(c), s2CharacterCount.get(c)))
.sum();
}

public static Map<Character, Integer> getCharacterCount(String s) {
Map<Character, Integer> characterCount = new HashMap<>();
for (char c: s.toCharArray()) {
characterCount.put(c, characterCount.computeIfAbsent(c, count -> 0) + 1);
}
return characterCount;
}

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

public int count(String str1, String str2) {
int result = 0;
if (str1.length() == 0 || str2.length() == 0)
return result;
if (str1.length() > str2.length()) {
for (int i = 0; i < str2.length(); i++) {
if (str2.charAt(i) == str1.charAt(i))
result++;
}
}
else {
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == str2.charAt(i))
result++;
}
}
return result;
}


Related Topics



Leave a reply



Submit