在两个字符串中查找常见字符 [英] Finding common characters in two strings
问题描述
我正在为必须对两个字符串中的公共字符数进行计数的问题进行编码。计数的主要部分是这样的
I am coding for the problem in which we got to count the number of common characters in two strings. Main part of the count goes like this
for(i=0; i < strlen(s1); i++) {
for(j = 0; j < strlen(s2); j++) {
if(s1[i] == s2[j]) {
count++;
s2[j] = '*';
break;
}
}
}
这与O( n ^ 2)逻辑。但是,我没有想到比这更好的解决方案了。谁能帮助我进行O(n)逻辑编码。
This goes with an O(n^2) logic. However I could not think of a better solution than this. Can anyone help me in coding with an O(n) logic.
推荐答案
这很简单。取两个 int
数组 freq1
和 freq2
的数组。将其所有元素初始化为 0
。然后读取您的字符串并将字符的频率存储到这些数组中。之后,比较数组 freq1
和 freq2
来查找公共字符。
This is very simple. Take two int
arrays freq1
and freq2
. Initialize all its elements to 0
. Then read your strings and store the frequencies of the characters to these arrays. After that compare the arrays freq1
and freq2
to find the common characters.
这篇关于在两个字符串中查找常见字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!