Question:
You are given a string s. Write a function to reverse the string.
Function Signature:
def reverse_string(s: str) -> str:
pass
Input:
- A string s consisting of lowercase and/or uppercase letters.
Output:
- A string consisting of letters from s in reverse order.
Example:
assert reverse_string("Hello World") == "dlroW olleH"
assert reverse_string("Racecar") == "racecaR"
Explanation:
To reverse a string, we can use a two-pointer approach. One pointer starts from the beginning of the string and moves forward, while the other pointer starts from the end of the string and moves backward.
- Initialize an empty string result to store the reversed string.
- Initialize a variable i to 0, representing the pointer starting from the beginning of the string.
- Initialize a variable j to the length of the string minus 1, representing the pointer starting from the end of the string.
- Iterate while i is less than or equal to j:
- Append the character at index j to the result string.
- Decrement j by 1.
- Append the character at index i to the result string.
- Increment i by 1.
- If the length of the string is odd, there will be one character left at the middle index. Append this character to the result string.
- Return the result string as the reversed string.
The time complexity of this solution is O(n), where n is the length of the input string.