Simple Text Editor


Problem Statement :


In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4  types:

1. append(W) - Append W string  to the end of S.
2 . delete( k ) - Delete the last k characters of S.
3 .print( k ) - Print the kth character of S.
4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2, reverting S to the state it was in prior to that operation.


Input Format


The first line contains an integer, Q, denoting the number of operations.
Each line i of the Q subsequent lines (where 0 < = i  < Q ) defines an operation to be performed. Each operation starts with a single integer, t  , denoting a type of operation as defined in the Problem Statement above. If the operation requires an argument,  is followed by its space-separated argument. For example, if t = 1  and , W = "abcd" line i will be 1 abcd.


Output Format

Each operation of type 3 must print the kth  character on a new line.



Solution :


                            Solution in C :

In C++ :



#include <iostream>
#include <string>
#include <stack>

int main() {

    std::string text, arg;
    int cmd;
    std::stack<std::string> history;
    
    std::cin >> cmd;
    while (std::cin >> cmd) {
        switch (cmd) {
            case 1: // Append
                std::cin >> arg;
                history.push(text);
                text.append(arg);
                break;
            case 2: // Erase
                std::cin >> cmd;
                history.push(text);
                text.erase(text.length() - cmd);
                break;
            case 3: // Get
                std::cin >> cmd;
                std::cout << text[cmd - 1] << '\n';
                break;
            case 4: // Undo
                text = std::move(history.top());
                history.pop();
                break;
        }        
    }
    return 0;
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
      
        Scanner sc = new Scanner(System.in);
        String str = "";
        int top = 0;
        int q = Integer.parseInt(sc.nextLine());
        MyStack stack = new MyStack(q);
        for(int i = 0; i < q; ++i){
            String st[] = sc.nextLine().split(" ");
            int query = Integer.parseInt(st[0]);
            if(query == 1){
                Node newNode = new Node(query,str.length());
                stack.top++;
                stack.list[stack.top] = newNode;
                str += st[1];
            } else if(query == 2){
                int k = Integer.parseInt(st[1]);
                Node newNode = new Node(query,str.substring(str.length()-k));
                stack.top++;
                stack.list[stack.top] = newNode;
                str = str.substring(0,str.length()-k);
            } else if(query == 3){
                int index = Integer.parseInt(st[1]);
                System.out.println(str.charAt(index-1));
            } else if(query == 4){
                Node newNode = stack.list[stack.top];
                stack.top--;
                if(newNode.qtype == 1){
                    str = str.substring(0,newNode.idx);
                } else if(newNode.qtype == 2){
                    str += newNode.w;
                }
            }
        }
    }
}
class MyStack{
    Node list[];
    int top;
    MyStack(int size){
        this.list = new Node[size];
        this.top = -1;
    }
}
class Node{
    int qtype;
    int idx;
    String w;
    Node(int x, String y){
        this.qtype = x;
        this.w = y;
    }
    Node(int x, int index){
        this.qtype = x;
        this.idx = index;
    }
}








In C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define STACK_SIZE 1000000
#define MAX_W_SIZE ((1000000) + (1))

char* stack[STACK_SIZE];
int sp = -1;

int is_empty() {
    return (sp < 0);
}

int is_full() {
    return (sp > STACK_SIZE);
}

void push(char* cp) {
    if (!is_full()) {
        stack[++sp] = cp;
    }
}

char* peek() {
    char* top = '\0';
    if (!is_empty()) {
        top = stack[sp];
    }
    return top;
}

char* pop() {
    char* top = peek();
    if (top) {
        stack[sp--] = '\0';
    }
    return top;
}

int get_len(char* warg) {
    int len = 0;
    while(*warg) {
        len++; warg++;
    }
    return len;
}
void do_append(char* warg) {
    int len = get_len(warg);
    
    char* current = peek();
    if (!current) {
        current = (char*) malloc(sizeof(char) * (len + 1));
        for (int i = 0; i < len; i++) {
        current[i] = warg[i];
        }
        current[len] = '\0';
        push(current);
    } else {
		int j = 0;
        int current_len = get_len(current);
        char* current_new = (char*)malloc(sizeof(char) * (current_len + len + 1));
        
        if (current_new) {
            for (int i = 0; i < current_len; i++) {
                current_new[i] = current[i];
            }
			for (int i = current_len; i < current_len + len; i++) {
				current_new[i] = warg[j++];
			}
            current_new[current_len + len] = '\0';
            push(current_new);
        }
    }   
}

void do_erase(int iarg) {
    char* current = peek();
    
    if (current) {
        int current_len = get_len(current);
        if (current_len >= iarg) {
            char* current_new = (char*)malloc(sizeof(char) * (current_len - iarg + 1));
            if (current_new) {
                for (int i = 0; i < current_len - iarg; i++) {
                    current_new[i] = current[i];
                }
                current_new[current_len - iarg] = '\0';
                push(current_new);
            }
        }
    }
}

void do_get(int iarg, char* ch) {
    char* current = peek();
    
    if (current) {
        int current_len = get_len(current);
        if (current_len >= iarg) {
            *ch = current[iarg - 1];   
        }
    }
}

void do_undo() {
    pop();
}

int main() {

    int Q;
    int op;
    int iarg;
    char warg[MAX_W_SIZE];
    scanf("%d", &Q);
    
    for (int i = 0; i < Q; i++) {
        scanf("%d", &op);
        
        if (op == 1) {
            scanf("%s", warg);
            do_append(warg);
        } else if (op == 2) {
            scanf("%d", &iarg);
            do_erase(iarg);
        } else if (op == 3) {
            scanf("%d", &iarg);
            char ch = '\0';
            do_get(iarg, &ch);
            fflush(stdout);
            printf("%c\n", ch);
        } else if (op == 4) {
            do_undo();
        }
    }
    return 0;
}








In Python3 :






q = int(input())
stack = ['']
for _ in range(q):
    o_type, *par = input().split()
    o_type = int(o_type)
    if o_type in (1, 2, 3):
        par = par[0]
        if o_type in (2, 3):
            par = int(par)

    if o_type == 1:
        stack.append(stack[-1] + par)
    elif o_type == 2:
        stack.append(stack[-1][:-par])
    elif o_type == 3:
        print(stack[-1][par - 1])
    elif o_type == 4:
        stack.pop()
                        




View More Similar Problems

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →