Simple Text Editor

  • + 0 comments

    Java 15

    import java.io.*;
    import java.util.*;
    
    class Operation {
        int type;
        String value;
        public Operation(int type, String value) {
            this.type = type;
            this.value = value;
        }
    }
    
    public class Solution {
        
        private static StringBuilder text = new StringBuilder("");
        
        // trace append and delete operations
        private static Stack<Operation> trace = new Stack<>(); 
        
        public static void main(String[] args) {
            
            Scanner scan = new Scanner(System.in);
            int q = scan.nextInt();
            for(int i = 0; i < q; i++) {
            int operation = scan.nextInt();
           
                switch(operation) {
                    case 1:
                    String newText = scan.next();
                    trace.push(new Operation(1, newText));
                    add(newText);
                    break;
                    
                    case 2:
                    int numToDelete = scan.nextInt();
                    int textLen = text.length();
                    trace.push(new Operation(2, text.substring(textLen - numToDelete, textLen)));
                    delete(numToDelete);
                    break;
                    
                    case 3:
                    int indextToPrint = scan.nextInt();
                    System.out.println(text.charAt(indextToPrint-1));
                    break;
     
                    case 4:
                    undo();
                    break;
                }
            }
            scan.close();
        }
        
        
        private static void delete(int numToDelete) {
            int textLen = text.length();
            String tempText = text.substring(0, textLen - numToDelete);
            text.setLength(0);
            text.append(tempText);
        }
        
        private static void add(String newText) {
            text.append(newText);
        }
        
        private static void undo() {
            if(!trace.isEmpty()) {
                Operation lastOperation = trace.pop();
                if(lastOperation.type == 1) {
                    delete(lastOperation.value.length());
                } else {
                    add(lastOperation.value);
                }
            }
        }
    }