Title:
Write a function reverse_string(s: str) -> str to implement string reversal.
Requirements:
You cannot use the built-in reversed() function or slicing [::-1] (but you can use them to verify the result).
Try to implement it using at least two different methods (for example, using loops, using the stack concept, etc.)..
Hint:
Method 1 (Loop): Initialize an empty string result. Start from the last character of the original string and traverse backwards, appending each character to the end of result.
Method 2 (Stack): The Last In First Out (LIFO) characteristic of strings fits the stack concept. You can push each character of the string onto a stack, then pop the top character to concatenate into a new string.
# Method 1: Loop (Concatenating from back to front)
def reverse_string(s):
result = ""
for i in range(len(s) - 1, -1, -1): # Start from len(s)-1, end at 0, step -1
result += s[i]
return result
# Method 2: Using a list to simulate a stack
def reverse_string(s):
stack = list(s) # Push string characters onto the stack (list)
result = ""
while stack: # While the stack is not empty
result += stack.pop() # Pop the top element (last character of the original string) and add to result
return result
# Test
print(reverse_string("hello")) # Output: "olleh"
print(reverse_string("Python")) # Output: "nohtyP"