Skip to content

Instantly share code, notes, and snippets.

@mithuns
Last active January 22, 2016 02:00
Show Gist options
  • Save mithuns/7570d8b11c8151f921f4 to your computer and use it in GitHub Desktop.
Save mithuns/7570d8b11c8151f921f4 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static class Node<TYPEA, TYPEB>
{
final TYPEA action;
final TYPEB text;
public Node(final TYPEA vala, final TYPEB valb)
{
action = vala;
text = valb;
}
}
static StringBuffer removeBlankSpace(final StringBuffer sb)
{
int j = 0;
for (int i = 0; i < sb.length(); i++)
{
if (!Character.isWhitespace(sb.charAt(i)))
{
sb.setCharAt(j++, sb.charAt(i));
}
}
sb.delete(j, sb.length());
return sb;
}
public static void main(final String[] args)
{
final Stack<Node> myStack = new Stack<Node>();
StringBuffer strBuf = new StringBuffer();
final Scanner scan = new Scanner(System.in);
final int Q = scan.nextInt();
for (int i = 0; i < Q; i++)
{
final int command = scan.nextInt();
switch (command)
{
case 1:
final String text = scan.nextLine().trim();
strBuf.append(text);
strBuf = removeBlankSpace(strBuf);
final Node<Integer, String> nodeAppend = new Node<Integer, String>(command, text);
myStack.push(nodeAppend);
break;
case 2:
final int textLen = scan.nextInt();
final Node<Integer, String> nodeErase = new Node<Integer, String>(command, strBuf.substring(strBuf.length() - textLen));
strBuf.delete(strBuf.length() - textLen, strBuf.length());
myStack.push(nodeErase);
break;
case 3:
final int k = scan.nextInt();
System.out.println(strBuf.charAt(k - 1));
break;
case 4:
final Node lastNode = myStack.pop();
// last being Append we Erase
if ((Integer) lastNode.action == 1)
{
final String lastText = (String) lastNode.text;
strBuf.delete(strBuf.length() - lastText.length(), strBuf.length());
}
else
// last being Erase we append
{
final String lastText = (String) lastNode.text;
strBuf.append(lastText);
}
break;
}
}
}
}
@mithuns
Copy link
Author

mithuns commented Jan 22, 2016

Updated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment