Simple Text Editor

  • + 0 comments
    public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            Scanner input = new Scanner(System.in);
            StringBuffer sb = new StringBuffer("");
            int q = input.nextInt();
            Stack<String> deletedString = new Stack<>();
            Stack<String> appendedString = new Stack<>();
            Stack<Integer> trace = new Stack<>();
            
            for(int j = 0; j < q; j++){
                int choose = input.nextInt();
                switch(choose){
                    case 1:
                        String str = input.next();
                        sb.append(str);
                        appendedString.push(str);
                        trace.push(1);
                        break;
                    case 2:
                        int k = input.nextInt();
                        int startIndex = Math.max(0, sb.length() - k);
                        deletedString.push(sb.substring(startIndex));
                        sb.delete(startIndex, sb.length());
                        trace.push(2);
                        break;
                    case 3:
                        int i = input.nextInt();
                        if(i > 0 && i <= sb.length()){
                            System.out.println(sb.charAt(i - 1));
                        }
                        break;
                    case 4:
                        if(!trace.isEmpty()){
                            int operate = trace.pop();
                            if(operate == 1){
                                String string = appendedString.pop();
                                sb.delete(sb.length() - string.length(), sb.length());
                            }
                            else if(operate == 2){
                                String string2 = deletedString.pop();
                                sb.append(string2);
                            }
                        }
                        
                        break;
                        
                }
            }
            input.close();
        }
    }