• + 1 comment

    STACK AND STRINGBUILDER SOLUTION

    import java.io.*;
    import java.util.*;
    
    class Solution {
        static class Pair
    	{
    		//to store the write and delete commands and operated strings in a stack
    		int opr;
    		String text;
    		Pair(int op, String s)
    		{
    			opr = op;
    			text = s;
    		}
    	}
    	public void SimpleTextEditor()
    	{
            Scanner sc = new Scanner(System.in);
    
    		//first line of input has length of string array
    		int n = Integer.parseInt(sc.nextLine().trim());
    		String[] operations = new String[n];
    
    		for(int i = 0; i < n; i++)
    			operations[i] = sc.nextLine();
    
    		//create stack to store operations of write and delete and string builder to store text
    		Stack<Pair> st = new Stack<>();
    		StringBuilder doc = new StringBuilder();
    
    		for(int i = 0; i < n; i++)
    		{
    			int command = operations[i].charAt(0) - '0';
    			if(command == 1)//append
    			{
    				String text = operations[i].substring(2);
    				st.push(new Pair(1, text));
    				doc.append(text);
    			}
    			else if(command == 2)//delete
    			{
    				int length = Integer.parseInt(operations[i].substring(2));
    				int startDelete = doc.length() - length;
    				int endDelete = doc.length();		
    				
    				st.push(new Pair(2, doc.substring(startDelete)));
    				doc.delete(startDelete, endDelete);
    			}
    			else if(command == 3)//print
    			{
    				int index =Integer.parseInt(operations[i].substring(2)) - 1;
    				System.out.println(doc.charAt(index));
    			}
    			else if(command == 4)//undo
    			{
    				Pair last = st.pop();
    					if(last.opr == 1)
    					{
    						int textlength = last.text.length();
    						int deleteStart = doc.length() - textlength;
    						doc.delete(deleteStart, doc.length());
    					}
    					else if(last.opr == 2)
    					{
    						String deleted = last.text;
    						doc.append(deleted);
    					}
    			}
    			else
    				System.out.println("INVALID");
    						
    		}
        }
    }
    
    public class Main {
        public static void main(String args[]) {
            Solution ob = new Solution();
            ob.SimpleTextEditor();
        }
    }