344. Reverse String #121
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
Topics: Write a function that reverses a string. The input string is given as an array of characters You must do this by modifying the input array in-place with Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Aug 26, 2024
Replies: 1 comment 2 replies
-
To solve this problem, we can follow these steps: Let's implement this solution in PHP: 344. Reverse String <?php
function reverseString(&$s) {
$left = 0;
$right = count($s) - 1;
while ($left < $right) {
// Swap the characters
$temp = $s[$left];
$s[$left] = $s[$right];
$s[$right] = $temp;
// Move the pointers
$left++;
$right--;
}
}
// Example 1:
$s1 = ["h", "e", "l", "l", "o"];
reverseString($s1);
print_r($s1); // Output: ["o", "l", "l", "e", "h"]
// Example 2:
$s2 = ["H", "a", "n", "n", "a", "h"];
reverseString($s2);
print_r($s2); // Output: ["h", "a", "n", "n", "a", "H"]
?> Explanation:
This solution has a time complexity of |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
basharul-siddike
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 344. Reverse String
Explanation:
Initialization: