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

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →