Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions 2399.check-distances-between-same-letters.js
Original file line number Diff line number Diff line change
@@ -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;
9 changes: 9 additions & 0 deletions checkDistances.test.js
Original file line number Diff line number Diff line change
@@ -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();
});