2109. Adding Spaces to a String #907
-
Topics: You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.
Return the modified string after the spaces have been added. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use an efficient approach with two pointers. Here's how the implementation in PHP 5.6 would look: Solution Explanation:
This approach ensures that we process the input efficiently, taking advantage of the sorted order of the Let's implement this solution in PHP: 2109. Adding Spaces to a String <?php
/**
* @param String $s
* @param Integer[] $spaces
* @return String
*/
function addSpaces($s, $spaces) {
$result = ""; // Initialize the resulting string
$spaceIndex = 0; // Pointer for the spaces array
$n = strlen($s); // Length of the string
$spacesCount = count($spaces); // Number of spaces to add
for ($i = 0; $i < $n; $i++) {
// If the current index matches the space index, add a space
if ($spaceIndex < $spacesCount && $i == $spaces[$spaceIndex]) {
$result .= " ";
$spaceIndex++;
}
// Append the current character to the result
$result .= $s[$i];
}
return $result;
}
// Example 1
$s1 = "LeetcodeHelpsMeLearn";
$spaces1 = [8, 13, 15];
echo addSpaces($s1, $spaces1) . "\n"; // Output: "Leetcode Helps Me Learn"
// Example 2
$s2 = "icodeinpython";
$spaces2 = [1, 5, 7, 9];
echo addSpaces($s2, $spaces2) . "\n"; // Output: "i code in py thon"
// Example 3
$s3 = "spacing";
$spaces3 = [0, 1, 2, 3, 4, 5, 6];
echo addSpaces($s3, $spaces3) . "\n"; // Output: " s p a c i n g"
?> Explanation:
This solution adheres to the constraints and is efficient even for large inputs. |
Beta Was this translation helpful? Give feedback.
We can use an efficient approach with two pointers. Here's how the implementation in PHP 5.6 would look:
Solution Explanation:
spaceIndex
to track the current position in thespaces
array.s
using a loop.spaces
array. If it does, append a space to the result and move thespaceIndex
pointer forward.This approach ensures that we process the input efficiently, taking advantage of the sorted order of the
spaces
array.Let's implement this solution in PHP: 2109. Adding Sp…