01 Feb Code Signal – 共用字符数(commonCharacterCount)
Objective
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc"
and s2 = "adcaa"
, the output should be commonCharacterCount(s1, s2) = 3
.
Strings have 3
common characters – 2
“a”s and 1
“c”.
Input/Output
- [execution time limit] 4 seconds (py3)
- [input] string s1A string consisting of lowercase English letters.Guaranteed constraints:
1 ≤ s1.length < 15
. - [input] string s2A string consisting of lowercase English letters.Guaranteed constraints:
1 ≤ s2.length < 15
.
Walkthrough
My idea for this was very simple – change the provided strings to lists, and then go through them and count the common characters, let’s look at an example:
- We get two strings
s1 = "aabcc"
s2 = "adcaa"
- Next we convert them to lists
s1_list = ['a', 'a', 'b', 'c', 'c']
s2_list = ['a', 'd', 'c', 'a', 'a']
- And create a counter
common=0
- Then we iterate through the the first list
s1_list
- check if the character ‘a’ exists in the
s2_list
- if so, we add + 1 to the counter,
- and delete the common character from the
s2_list
- check if the character ‘a’ exists in the
- At the end we return the counter variable
common
class Solution:
def commonCharacterCount(s1, s2):
s1_list = list(s1)
s2_list = list(s2)
print(s1_list)
print(s2_list)
common_count = 0
for i in s1_list:
for j in s2_list:
if i == j:
common_count += 1
s2_list.remove(j)
break
print(common_count)
commonCharacterCount(‘aabcc’, ‘adcaa’)
commonCharacterCount(‘aaacc’, ‘adccaa’)
commonCharacterCount(”, ”)
No Comments