Typing with backspace
Build text with a stack; backspace pops the last character. About 8 minutes.
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.
screen = []
for key in keys:
if key == "#":
if screen:
screen.pop()
else:
screen.append(key)
return "".join(screen)- screen
- "cat"
c, a, t: each letter is pushed onto the end of the screen.
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.
What's left on the screen after these keys?
keys = "ab#c#d"
- A"ad"
- B"abd"
- C"d"
Show the answer
"ad". a, ab, a, ac, a, ad. Each # removes the newest character.
Typed with backspaces
keys lists every key someone pressed, in order. Letters are typed as normal. A '#' is the backspace key: it deletes the last character on the screen, or does nothing if the screen is empty. Return the text left on the screen at the end.
keys = "cat#r##ow" → "cow"
0 ≤ length of keys ≤ 100,000 · keys has lowercase letters and #