Simple Text Editor

  • + 0 comments

    PYTHON SOLUTION

    APPEND = 1 DELETE = 2 PRINT = 3 UNDO = 4

    class TextEditor: def init(self, initial_str: str = ""): self.current_str = list(initial_str) self.stack = []

    def append(self, s: str):
    
            self.stack.append("".join(self.current_str))
    
            self.current_str.extend(s)
    
    def delete(self, k: int):
    
            self.stack.append("".join(self.current_str))
    
            self.current_str = self.current_str[:-k]
    
    def print(self, k: int):
    
            print(self.current_str[k-1])
    
    def undo(self):
    
            if self.stack:
                    self.current_str = list(self.stack.pop())
    
    def command(self, s: str):
    
            parts = s.split(maxsplit=1)
            op = int(parts[0])
    
            if op == APPEND:
                    self.append(parts[1])
            elif op == DELETE:
                    self.delete(int(parts[1]))
            elif op == PRINT:
    

    self.print(int(parts[1])) elif op == UNDO: self.undo()

    if name == "main": Q = int(input()) editor = TextEditor() for _ in range(Q): command = input().strip() editor.command(command)