Program to find final text in an editor by performing typing and backspacing in Python

Suppose we have a string s that represents characters that typed into an editor, the symbol "<-" indicates a backspace, we have to find the current state of the editor.

So, if the input is like s = "ilovepython<-<-ON", then the output will be "ilovepythON", as there are two backspace character after "ilovepython" it will delete last two character, then again type "ON".

To solve this, we will follow these steps −

  • res := a new list
  • for each i in s, do
    • if i is same as '-' and last character of res is same as '<', then
      • delete last element from res
      • if res is not empty, then
        • delete last element from res
    • otherwise,
      • insert i at the end of res
  • join the elements present in res and return

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, s):
      res = [] for i in s:
      if i == '-' and res[-1] == '< ': res.pop()
         if res:
      return "".join(res)
ob = Solution()