The screen is a stack
Each letter you type lands at the end of the text, and backspace deletes the last character, the newest one. That is push and pop again, like adding and removing plates from a pile.
This time the stack isn't a helper on the side: it is the text on the screen itself.
A letter: push it onto the end.
A hash mark: pop the last character, if there is one.
screen = []
for key in keys:
if key == "#":
if screen:
screen.pop()
else:
screen.append(key)
return "".join(screen)keys = "cat#r##ow"
c
0a
1t
2#
3r
4#
5#
6o
7w
8key
- screen
- "cat"
c, a, t: each letter is pushed onto the end of the screen.
Move 1 of 6
A stack of characters that turns into a string
In Python, keep a list of characters and join it at the end, and do the same in JavaScript with an array. In Java, a StringBuilder works as a stack: append adds, and deleting the last character removes. In C++, a string already is one, with push-back and pop-back.
The reason to avoid rebuilding the text each time is that it copies every character again.
Python and JavaScript: a list of characters, then join.
Java StringBuilder and C++ string: add and remove at the end.
Don't rebuild the text: cutting off the last character copies the whole text every time.