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 :



title-img


                            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

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →