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
- if i is same as '-' and last character of res is same as '<', then
- join the elements present in res and return
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): res = [] for i in s: if i == '-' and res[-1] == '< ': res.pop() if res: res.pop() else: res.append(i) return "".join(res) ob = Solution() print(ob.solve("ilovepython<-<-ON"))
Input
"ilovepython<-<-ON"
Output
ilovepython<-<-ON