awelgorithms

Reverse a string with a stack

Updated

Push each character, then pop to build a new string. Last character in is first character out, so the string reverses. Immutable strings need a buffer for the pops.

What to focus on

s = "abca" → push a,b,c,a → pop a,c,b,a → "acba". One character is identity. Do not reverse in place on the string. Reverse the stack of chars.

Worked examples

four

s = "abca"
  1. stack [a, b, c, a] top a
  2. pops a,c,b,a

Result: "acba"

one

s = "a"
  1. push a pop a

Result: "a"

two

s = "ab"
  1. push a,b
  2. pop b,a

Result: "ba"

Try it

Write reverseString(s). s is the string. Push each character, then pop into a new string. Return that string. "abca" becomes "acba". "a" stays "a". "ab" becomes "ba".

s is a string of letters. Length is at least 1.