diff --git a/2399.check-distances-between-same-letters.js b/2399.check-distances-between-same-letters.js new file mode 100644 index 00000000..8c7344d3 --- /dev/null +++ b/2399.check-distances-between-same-letters.js @@ -0,0 +1,41 @@ +/* URL of this problem + * https://leetcode.com/problems/check-distances-between-same-letters/description/ + * + * @param {string} s + * @param {number[]} distance + * @return {boolean} + */ + +var checkDistances = function(s, distance) { + for (let i = 0; i < distance.length; i++) { + // The range of Lowercase English letters on the UTF-16 code table are from 97 to 122. + // Get a matching English letter by adding each index of distance, staring from 0, and 97 + const Char = String.fromCharCode(97 + i); + const ElementCount = CountElementInbetween(s, Char); + + if (!s.includes(Char)) { + continue; + } + + if (distance[i] !== ElementCount) { + return false; + } + } + return true; +}; + +const CountElementInbetween = (str, char) => { + const Chars = [...str]; + const CharIndexes = []; + + Chars.forEach((element, idx) => { + if (element === char) { + CharIndexes.push(idx); + } + }); + + // Count the number of elements in between char + return Math.abs(CharIndexes[0] - CharIndexes[1]) - 1; +} + +module.exports = checkDistances; \ No newline at end of file diff --git a/checkDistances.test.js b/checkDistances.test.js new file mode 100644 index 00000000..78dd3e43 --- /dev/null +++ b/checkDistances.test.js @@ -0,0 +1,9 @@ +const checkDistances = require("./2399.check-distances-between-same-letters"); + +test("Return true if the input s is a well-spaced string", () => { + expect(checkDistances("abaccb", [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])).toBeTruthy(); +}); + +test("Return false if the input s is NOT a well-spaced string", () => { + expect(checkDistances("aa", [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])).toBeFalsy(); +}); \ No newline at end of file