Simple Text Editor

Sort by

recency

|

57 Discussions

|

  • + 0 comments
    x = ['']
    for s in [input() for _ in range(int(input()))]:
        x.append(x[-1]+s[2:]) if s[0] == '1' else x.append(x[-1][:-int(s[2:])]) if s[0] == '2' else print(x[-1][int(s[2:])-1]) if s[0] == '3' else x.pop() if s == '4' else ...
    
  • + 0 comments

    Here is HackerRank Simple Text Editor problem solution in Python, Java, C++, C and javascript

  • + 0 comments

    C#

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    
    class Editor {
        private StringBuilder _sb = new StringBuilder();
        private Stack<Action> _history = new Stack<Action>();
        
        public void Append(string s) {
            int start = _sb.Length;
            int len = s.Length;
            _history.Push(() => _sb.Remove(start, len));
            _sb.Append(s);
        }
        
        public void DeleteLast(int n) {
            string last = Substring(_sb.Length - n);
            _history.Push(() => _sb.Append(last));
            _sb.Remove(_sb.Length - n, n);
        }
        
        private string Substring(int start) {
            char[] buffer = new char[_sb.Length - start];
            
            for (int i = 0, j = start; j < _sb.Length; i++, j++)
                buffer[i] = _sb[j];
                
            return new string(buffer);
        }
        
        public char GetChar(int n) =>_sb[n - 1];
        
        public void Undo() {
            if (_history.Count > 0)
                _history.Pop()();
        }
    }
    
    class Solution {
        static void Main(String[] args) {
            var editor = new Editor();
            
            int q = Convert.ToInt32(Console.ReadLine());
            
            for (int i = 0; i < q; i++) {
                string[] parts = Console.ReadLine().Split(' ');
                int cmd = Convert.ToInt32(parts[0]);
                int k;
                
                switch (cmd) {
                    case 1:
                        editor.Append(parts[1]);
                        break;
                        
                    case 2:
                        k = Convert.ToInt32(parts[1]);
                        editor.DeleteLast(k);
                        break;
                    
                    case 3:
                        k = Convert.ToInt32(parts[1]);
                        char c = editor.GetChar(k);
                        Console.WriteLine(c);
                        break;
                        
                    case 4:
                        editor.Undo();
                        break;
                }
            }
        }
    }
    
  • + 0 comments

    Really poor test cases. Solutions that cache the entire string at every append / delete are getting accepted, whereas solutions that just do in-place updates are failing with TLE. Such accepted solutions will go out of memory if they were actually to be used as a text editor.

  • + 0 comments
    class Editor:
        def __init__(self):
            """Initialize the text editor."""
            self.text = ""
            self.history = []
    
        def append(self, word):
            """Append a word to the end of the text."""
            self.history.append(self.text)
            self.text += word
    
        def delete(self, k):
            """Delete the last k characters from the text."""
            if 0 <= k <= len(self.text):
                self.history.append(self.text)
                self.text = self.text[:-k]
            else:
                raise ValueError("Cannot delete more characters than the length of the text.")
    
        def print_char(self, k):
            """Print the character at the specified index in the text."""
            if 1 <= k <= len(self.text):
                print(self.text[k - 1])
            else:
                raise IndexError("Index out of range.")
    
        def undo(self):
            """Undo the last operation by restoring the previous state of the text."""
            if self.history:
                self.text = self.history.pop()
            else:
                print("Nothing to undo.")
    
    # Test the Editor class
    editor = Editor()
    count = int(input())
    for _ in range(count):
        operation = input().split()
        op_code = operation[0]
        try:
            if op_code == '1':
                editor.append(operation[1])
            elif op_code == '2':
                editor.delete(int(operation[1]))
            elif op_code == '3':
                editor.print_char(int(operation[1]))
            elif op_code == '4':
                editor.undo()
            else:
                print("Invalid operation code.")
        except (ValueError, IndexError) as e:
            print(f"Error: {e}")