2138. Divide a String Into Groups of Size k #1838
-
|
Topics: A string
Note that the partition is done so that after removing the Given the string Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to divide a given string into groups of size Approach
Let's implement this solution in PHP: 2138. Divide a String Into Groups of Size k <?php
/**
* @param String $s
* @param Integer $k
* @param String $fill
* @return String[]
*/
function divideString($s, $k, $fill) {
$n = strlen($s);
$result = array();
for ($i = 0; $i < $n; $i += $k) {
$chunk = substr($s, $i, $k);
if (strlen($chunk) < $k) {
$chunk = str_pad($chunk, $k, $fill, STR_PAD_RIGHT);
}
$result[] = $chunk;
}
return $result;
}
// Test cases
// Example 1
print_r(divideString("abcdefghi", 3, "x"));
// Output: Array ( [0] => abc [1] => def [2] => ghi )
// Example 2
print_r(divideString("abcdefghij", 3, "x"));
// Output: Array ( [0] => abc [1] => def [2] => ghi [3] => jxx )
?>Explanation:
This approach efficiently partitions the string into groups of the specified size, handling any necessary padding for the last group, and returns the result as an array of strings. |
Beta Was this translation helpful? Give feedback.
We need to divide a given string into groups of size
k. Each group should contain exactlykcharacters, except possibly the last group, which may need to be padded with a specified fill character if there aren't enough characters left in the string. The solution involves iterating through the string, extracting each group, and padding the last group if necessary.Approach
k. If the string length is not a multiple ofk, the last segment will have fewer thankcharacters, which need to be padded with the fill character to make its lengthk.k, we can extract each …