From a59ad3e8b5bb515d864beab6b6ea37c4fd2755c3 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Tue, 3 Jan 2023 09:32:47 -0800 Subject: [PATCH 1/2] solve 2138. Divide a String Into Groups of Size k --- 2138.divide-a-string-into-groups-of-size-k.js | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 2138.divide-a-string-into-groups-of-size-k.js diff --git a/2138.divide-a-string-into-groups-of-size-k.js b/2138.divide-a-string-into-groups-of-size-k.js new file mode 100644 index 00000000..376070a9 --- /dev/null +++ b/2138.divide-a-string-into-groups-of-size-k.js @@ -0,0 +1,28 @@ +/* URL of this problem + * https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/description/ + * + * @param {string} s + * @param {number} k + * @param {character} fill + * @return {string[]} + */ + +var divideString = function(s, k, fill) { + const Divided = []; + const LastGroupLen = s.length % k; + + for (let i = 0; i < s.length; i += k) { + const Substr = s.substring(i, i + k); + + Divided.push(Substr); + } + // A character fill is used to complete the group + // if the length of the last group does not have k characters remaining. + if (LastGroupLen > 0 && LastGroupLen < k) { + Divided[Divided.length -1] += fill.repeat(k - LastGroupLen); + } + + return Divided; +}; + +module.exports = divideString; \ No newline at end of file From 6bf0b0de43b93a339bab53ef87f92adbc3daaa97 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Tue, 3 Jan 2023 09:33:33 -0800 Subject: [PATCH 2/2] test function divideString --- divideString.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 divideString.test.js diff --git a/divideString.test.js b/divideString.test.js new file mode 100644 index 00000000..106ddbe1 --- /dev/null +++ b/divideString.test.js @@ -0,0 +1,13 @@ +const divideString = require("./2138.divide-a-string-into-groups-of-size-k"); + +test("Return the divided groups, each of them has exactyly k characters", () => { + expect(divideString("abcdefghi", 3, "x")).toEqual(["abc","def","ghi"]); +}); + +test("Return the divided groups, every group of them but the last one has exactly k characters", () => { + expect(divideString("abcdefghij", 3, "x")).toEqual(["abc","def","ghi","jxx"]); +}); + +test("Return the divided groups, the last group of them is not filled with the character fill if the character fill is empty", () => { + expect(divideString("abcdefghij", 3, "")).toEqual(["abc","def","ghi","j"]); +});