See the original problem on HackerRank.
Solutions
This is a classical challenge requiring stacks.
A C++ solution:
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
|
#include <string>
#include <stack>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string S, tmp; //S.reserve(1000000);
int Q, op, K; cin >> Q;
stack<string> states;
while (Q--)
{
cin >> op;
switch(op)
{
case 1:
states.push(S);
cin >> tmp;
S.append(tmp);
break;
case 2:
states.push(S);
cin >> K;
S.erase(S.end()-K, S.end());
break;
case 3:
cin >> K;
cout << S[K-1] << endl;
break;
case 4:
S = move(states.top());
states.pop();
break;
}
}
}
|
A Haskell solution:
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
|
data State = State String [String]
atIndex k lst = lst !! (length lst - k)
edit fn (State o (x:xs)) = State o (fn x:x:xs)
out fn (State o (x:xs)) = State (fn o x) (x:xs)
undo (State o xs) = State o (drop 1 xs)
-- reverse is needed for better performance
append w x = reverse w ++ x
printChar k o x = '\n':atIndex k x:o
cmd ('1':' ':param) = edit . append $ param
cmd ('2':' ':param) = edit . drop . read $ param
cmd ('3':' ':param) = out . printChar . read $ param
cmd "4" = undo
runOne state command = command state
runAll = foldl runOne (State "" [""])
takeOutput (State o _) = reverse o
main = do
_ <- getLine
contents <- getContents
putStr . takeOutput . runAll $ cmd <$> lines contents
|