Write a function that takes a string s and returns it with its characters in reverse order. The function should run in O(n) time and use O(1) extra space, not counting the space needed to store the result. Reverse the characters in place where the language allows it; otherwise, use no more extra space than necessary.
Function Signature
def reverse_string(s: str) -> str:
Rules
-
Every element of the Python string is one character, including spaces and punctuation. The character at index
i
of the output is
s[len(s) - 1 - i]
.
-
The output has the same length as
s
, and every character keeps its case.
Constraints
Examples
Input: s = "hello"
Output: "olleh"
Reading "hello" from the last character to the first gives o, l, l, e, h.
Input: s = "Python"
Output: "nohtyP"
The capital P moves from the front to the end and stays uppercase.
Input: s = "race car"
Output: "rac ecar"
The space counts as a character. It sits at index 4 of the input and ends up at index 3 of the output, since 8 - 1 - 4 = 3.