-
Notifications
You must be signed in to change notification settings - Fork 110
/
solution.java
96 lines (82 loc) · 2.31 KB
/
solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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);
int q = sc.nextInt();
Stack<String> stack = new Stack<String>();
String s = "";
for (int x = 0; x < q; x++) {
int ope = sc.nextInt();
switch (ope) {
case 1: //append
stack.push(s);
String append = sc.next();
s += append;
break;
case 2: //erase last x characters
stack.push(s);
int character = sc.nextInt();
s = s.substring(0, s.length() - character);
break;
case 3: //print
int index = sc.nextInt();
System.out.println(s.charAt(index - 1));
break;
case 4: //undo
s = stack.pop();
break;
default:
break;
}
}
}
}
/*
You can also do this problem by using below code :
import java.util.Scanner;
import java.util.Stack;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder S = new StringBuilder();
Stack<Operation> operations = new Stack<Operation>();
int Q = sc.nextInt();
for (int i = 0; i < Q; i++) {
int type = sc.nextInt();
if (type == 1) {
String W = sc.next();
S.append(W);
operations.push(new Operation(type, W.length()));
} else if (type == 2) {
int k = sc.nextInt();
String last = S.substring(S.length() - k);
S.delete(S.length() - k, S.length());
operations.push(new Operation(type, last));
} else if (type == 3) {
int k = sc.nextInt();
System.out.println(S.charAt(k - 1));
} else {
Operation operation = operations.pop();
if (operation.type == 1) {
S.delete(S.length() - (int) operation.argument, S.length());
} else {
S.append(operation.argument);
}
}
}
sc.close();
}
}
class Operation {
int type;
Object argument;
Operation(int type, Object argument) {
this.type = type;
this.argument = argument;
}
}
*/