-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample25.java
80 lines (62 loc) · 2.28 KB
/
Example25.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
package applications.algorithms;
import datastructs.adt.ArrayStack;
import java.util.Scanner;
/** Category: Algorithms
* ID: Example25
* Description: Implement a simple text editor
* Taken From: HackerRank Simple Text Editor
* Details:
* In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, .
* You must perform operations of the following
*
* types:
*
* 1 append(W) - Append string W to the end of S
* 2 delete(k) - Delete the last k characters of S
* 3 print(k) - Print the k-th character of S
* 4 undo() - Undo the last (not previously undone) operation of type or , reverting
* to the state it was in prior to that operation.
*
* Input Format
*
*/
public class Example25 {
public static void main(String[] args){
// An ArrayStack that holds the state of the editor
// upd to 50 states can be held
ArrayStack<String> stack = new ArrayStack<>(50);
// initially the editor is empty
String editor = "";
boolean stop = false;
Scanner input = new Scanner(System.in);
while(!stop){
System.out.println("Enter and operation: ");
String input_type = input.nextLine();
System.out.println("Input given: " + input_type);
if(input_type.equals("append")){
System.out.println("Enter append data: ");
input_type = input.nextLine();
stack.push(editor);
// add some item to the editor
editor += input_type;
}
else if(input_type.equals("print")){
System.out.println(editor);
}
else if(input_type.equals("delete")){
System.out.println("Enter how many characters to delete: ");
input_type = input.nextLine();
int val = Integer.valueOf(input_type);
stack.push(editor);
editor = editor.substring(0, editor.length()-val);
}
else if(input_type.equals("undo")){
editor = stack.pop();
}
else if(input_type.equals("stop")){
System.out.println("Stopping:...");
stop = true;
}
}
}
}