[JavaScript 刷题] Code Signal - 共用字符数(commonCharacterCount)
代码
1575 人阅读
|
0 人回复
|
<
[JavaScript 刷题] Code Signal - 共用字符数(commonCharacterCount)
标题问题地点:commonCharacterCount
标题问题
以下:
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 (js)
- [input] string s1
A string consisting of lowercase English letters.
Guaranteed constraints:
1 ≤ s1.length < 15.
- [input] string s2
A string consisting of lowercase English letters.
Guaranteed constraints:
1 ≤ s2.length < 15.
- [output] integer
解题思路
实在那一讲题战上一讲刷的 Code Signal - 一切最少字符串(all longest strings) 有面类似的处所,皆是对数组举办迭代,最初将迭代的成果以键值对的方法举办存储。
不外那里存储的键值对是 字符-呈现次数。
正在 s1 战 s2 的字符皆有了,以后要做的事情便是寻觅两个字符串订交的字符,将订交的字符数字相减,就可以找到终极的成果。
别的需求留意一面的便是,订交的字符利用的是 Math.min() 来举办供值的操纵。
那题对我次要的磨练仍是 Map 的函数挪用,那圆里确实卡的有面暂。别的,需求留意的是,s1Map.keys() 返回的是一个迭代器,其实不能间接利用 Array 的函数举办操纵。没有利用 Array.from(s1Map.keys()) 转换也能够利用 [...s1Map.keys()] 的方法举办隐式转换。
利用 JavaScript 解题
- function commonCharacterCount(s1, s2) {
- const s1Map = getAllOccurance(s1);
- const s2Map = getAllOccurance(s2);
- const intersection = Array.from(s1Map.keys()).filter((key) => s2Map.has(key));
- let sum = 0;
- for (const key of intersection) {
- sum += Math.min(s1Map.get(key), s2Map.get(key));
- }
- return sum;
- }
- const getAllOccurance = (str) => {
- const map = new Map();
- for (const char of str) {
- if (map.has(char)) {
- const updatedVal = map.get(char) + 1;
- map.set(char, updatedVal);
- } else {
- map.set(char, 1);
- }
- }
- return map;
- };
复造代码 免责声明:假如进犯了您的权益,请联络站少,我们会实时删除侵权内乱容,感谢协作! |
1、本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,按照目前互联网开放的原则,我们将在不通知作者的情况下,转载文章;如果原文明确注明“禁止转载”,我们一定不会转载。如果我们转载的文章不符合作者的版权声明或者作者不想让我们转载您的文章的话,请您发送邮箱:Cdnjson@163.com提供相关证明,我们将积极配合您!
2、本网站转载文章仅为传播更多信息之目的,凡在本网站出现的信息,均仅供参考。本网站将尽力确保所提供信息的准确性及可靠性,但不保证信息的正确性和完整性,且不对因信息的不正确或遗漏导致的任何损失或损害承担责任。
3、任何透过本网站网页而链接及得到的资讯、产品及服务,本网站概不负责,亦不负任何法律责任。
4、本网站所刊发、转载的文章,其版权均归原作者所有,如其他媒体、网站或个人从本网下载使用,请在转载有关文章时务必尊重该文章的著作权,保留本网注明的“稿件来源”,并自负版权等法律责任。
|
|
|
|
|