Algorithm to Reverse a String
Problem Statement
Write a program to reverse a given string without using any built-in reverse methods or functions. The program should take a string as input and output the string in reverse order.
Approach
- Input Validation:
- Ensure the input is a valid string.
- Iterative Method:
- Use a loop to iterate over the string from the end to the beginning.
- Append each character to a new string.
- Alternative Methods:
- Use two-pointer technique to swap characters in place (if working with mutable data structures, such as arrays).
- Output:
- Return or print the reversed string.
Steps
- Initialize an empty string (
reversed
). - Traverse the original string from the last character to the first using a decrementing loop.
- Append each character to the
reversed
string. - Return the reversed string.
class StringReverser
# Method to reverse a string
def self.reverse_string(input)
validate_input(input) # Validate the input
reversed = "" # Initialize an empty string for the reversed result
# Iterate over the string from the end to the beginning
(input.length - 1).downto(0) do |index|
reversed += input[index]
end
reversed
end
private
# Input validation to ensure the input is a string
def self.validate_input(input)
unless input.is_a?(String)
raise ArgumentError, "Input must be a valid string."
end
end
end
# Example Usage
if __FILE__ == $0
input_string = "hello"
puts "Original String: #{input_string}"
puts "Reversed String: #{StringReverser.reverse_string(input_string)}"
# Test Cases
require 'rspec/autorun'
RSpec.describe StringReverser do
describe '.reverse_string' do
context 'when input is a valid string' do
it 'reverses a normal string' do
expect(StringReverser.reverse_string("hello")).to eq("olleh")
end
it 'returns an empty string when input is empty' do
expect(StringReverser.reverse_string("")).to eq("")
end
it 'reverses a single-character string' do
expect(StringReverser.reverse_string("a")).to eq("a")
end
it 'reverses a string with spaces' do
expect(StringReverser.reverse_string("hello world")).to eq("dlrow olleh")
end
end
context 'when input is invalid' do
it 'raises an error for non-string input' do
expect { StringReverser.reverse_string(12345) }.to raise_error(ArgumentError, "Input must be a valid string.")
end
it 'raises an error for nil input' do
expect { StringReverser.reverse_string(nil) }.to raise_error(ArgumentError, "Input must be a valid string.")
end
end
end
end
end
Run this Code
Save the Ruby code in a file named StringReverser.rb
and execute it using the command: ruby StringReverser.rb
.