A string s can be partitioned into groups of size k using the following procedure:
- The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.
- For the last group, if the string does not have k characters remaining, a character fill is used to complete the group.
Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.
Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.
출처:https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/description/
풀이
function divideString(s: string, k: number, fill: string): string[] {
const partition = [];
for(let i=0; i<s.length; i+=k) {
const chunk = s.substring(i, i+k);
if(chunk.length === k) partition.push(chunk);
else partition.push(chunk + fill.repeat(k - chunk.length));
}
return partition;
};
- substring(i, i+k)를 사용하여 현재 인덱스 i부터 i+k 길이만큼의 부분 문자열을 chunk에 저장
- chunk의 길이가 k보다 짧다면, fill 문자를 k - chunk.length 만큼 반복하여 부족한 부분을 채운 후, 이를 chunk와 결합하여 partition 배열에 추가
'LeetCode' 카테고리의 다른 글
| 1598. Crawler Log Folder / TypeScript (0) | 2024.06.15 |
|---|---|
| 2946. Matrix Similarity After Cyclic Shifts / TypeScript (1) | 2024.06.13 |
| 868. Binary Gap / TypeScript (0) | 2024.06.10 |
| 3033. Modify the Matrix / TypeScript (1) | 2024.06.09 |
| 2325. Decode the Message (1) | 2024.06.06 |