[路飞] 5980. 将字符串拆分为若干长度为 k 的组

125 阅读1分钟

题目描述

leetcode-cn.com/problems/di…

这是一道周赛题

image.png

解题思路

算法

模拟

思路

题目有两个重点:

  • k 个一组,
  • 不够 k 个的话填充字符

首先,我们用一个 index 标记当前遍历到的字符,这是保证组数符合要求且生成每组字符串的过程中保证首先用字符串 s 的字符,然后再用 fill 在每组的填充过程中,首先保证这组(用数组表示)的长度是 k,我们用 Array.prototype.fill 先把所有的元素填充成 fill

根据上面的原则,

我们遍历字符串,在遍历的过程中,用一个变量 index 来指向当前遍历到的字符串索引

用一个 while 循环生成一组,通过一个计数器 cnt(初始值为 0),我们让循环中值得条件是 cnt === kindex 已经越界,所以我们每一组实际上在一开始是 kfill,在生成过程中不断地替换元素,如果循环结束,我们就停止替换

代码

/**
 * @param {string} s
 * @param {number} k
 * @param {character} fill
 * @return {string[]}
 */
var divideString = function (s, k, fill) {
  const arr = []
  let index = 0

  while (index < s.length) {
    let cur = new Array(k).fill(fill)
    let count = 0
    while (count < k && index < s.length) {
      cur[count] = s[index++]
      count++
    }

    arr.push(cur.join(""))
  }

  return arr
}