DEV Community

almokhtar bekkour
almokhtar bekkour

Posted on

Check if string is palindrome without String#reverse

def palindrome?(str)
  reversed_str = ''
  i = str.length - 1
  while i >= 0
    reversed_str += str[i]
    i -= 1
  end
  reversed_str == str
end
Enter fullscreen mode Exit fullscreen mode

specs

describe "palindrome?" do
    it "should accept a string as an arg" do
      expect { palindrome?("tot") }.to_not raise_error
    end

    context "when the string is the same forwards and backwards" do
      it "should return true" do
        expect(palindrome?("tot")).to eq(true)
        expect(palindrome?("racecar")).to eq(true)
        expect(palindrome?("madam")).to eq(true)
        expect(palindrome?("aa")).to eq(true)
        expect(palindrome?("a")).to eq(true)
      end
    end

    context "when the string is not the same forwards and backwards" do
      it "should return false" do
        expect(palindrome?("cat")).to eq(false)
        expect(palindrome?("greek")).to eq(false)
        expect(palindrome?("xabcx")).to eq(false)
      end
    end

    it "should not use String#reverse" do
      expect_any_instance_of(String).to_not receive(:reverse)
      palindrome?("tot")
    end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
moopet profile image
Info Comment hidden by post author - thread only accessible via permalink
Ben Sinclair

If this was for a test, to see if you could check whether a string was a palindrome without using an explicit reverse method, then I'd say it was against the spirit of the question to write your own reverse function. I guess it's a contrived interview type problem, and I think if I was conducting the interview I'd want to see something different.

Some comments have been hidden by the post's author - find out more