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
Jesse and Cookies
Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t
View Solution →Find the Running Median
The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.
View Solution →Minimum Average Waiting Time
Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h
View Solution →Merging Communities
People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w
View Solution →Components in a graph
There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu
View Solution →Kundu and Tree
Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that
View Solution →