From ef1a11003e04eb64e0e18bb15da8b81abe219241 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Wed, 4 Jan 2023 18:21:41 -0800 Subject: [PATCH 1/2] solve 2068. Check Whether Two Strings are Almost Equivalent --- ...ether-two-strings-are-almost-equivalent.js | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 2068.check-whether-two-strings-are-almost-equivalent.js diff --git a/2068.check-whether-two-strings-are-almost-equivalent.js b/2068.check-whether-two-strings-are-almost-equivalent.js new file mode 100644 index 00000000..1761f57f --- /dev/null +++ b/2068.check-whether-two-strings-are-almost-equivalent.js @@ -0,0 +1,31 @@ +/* URL of this problem + * https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/description/ + * + * @param {string} word1 + * @param {string} word2 + * @return {boolean} + */ + +var checkAlmostEquivalent = function(word1, word2) { + const Word1CharsByFreq = new Map(); + const Word2CharsByFreq = new Map(); + const UniqueChars = [...new Set(word1 + word2)]; + const MaximumFrequency = 3; + + for (let i = 0; i < word1.length; i++) { + Word1CharsByFreq.set(word1[i], (Word1CharsByFreq.get(word1[i]) ?? 0) + 1); + Word2CharsByFreq.set(word2[i], (Word2CharsByFreq.get(word2[i]) ?? 0) + 1); + } + for (let i = 0; i < UniqueChars.length; i++) { + const Word1CharFreq = Word1CharsByFreq.get(UniqueChars[i]) ?? 0; + const Word2CharFreq = Word2CharsByFreq.get(UniqueChars[i]) ?? 0; + const Difference = Math.abs(Word1CharFreq - Word2CharFreq); + + if (Difference > MaximumFrequency) { + return false; + } + } + return true; +}; + +module.exports = checkAlmostEquivalent; \ No newline at end of file From 2ee35a15067839eaa6ee4e318e4c075956768cfc Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Wed, 4 Jan 2023 18:22:10 -0800 Subject: [PATCH 2/2] test function checkAlmostEquivalent --- checkAlmostEquivalent.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 checkAlmostEquivalent.test.js diff --git a/checkAlmostEquivalent.test.js b/checkAlmostEquivalent.test.js new file mode 100644 index 00000000..b289f95e --- /dev/null +++ b/checkAlmostEquivalent.test.js @@ -0,0 +1,13 @@ +const checkAlmostEquivalent = require("./2068.check-whether-two-strings-are-almost-equivalent"); + +test("Return true if word1 and word2 comprise the same letters and frequency differences of all the letters are less than 3", () => { + expect(checkAlmostEquivalent("abcaccc", "abaaacc")).toBeTruthy(); +}); + +test("Return true if there is a letter which does not exist in either word1 or word2 and frequency differences of all the letters are less than 3", () => { + expect(checkAlmostEquivalent("cccddabba", "babababab")).toBeTruthy(); +}); + +test("Return false if there is a letter which exists in both word1 and word2 or either of them has more than 3 frequency differences", () => { + expect(checkAlmostEquivalent("aaaa", "bccb")).toBeFalsy(); +}); \ No newline at end of file