hackerrank :Simple Text Editor 简单文本编辑器

原题见这里

Simple Text Editor 是一个包含undo操作的文本编辑器,追加、删除、查询都通过 StringBuilder 实现,undo通过栈实现。

hackerrank :Simple Text Editor 简单文本编辑器_第1张图片
Simple Text Editor

import java.util.*;

/**
 * Simple Text Editor
 * https://www.hackerrank.com/challenges/simple-text-editor/problem
 * 
 * @author lishoujun
 */
public class SimpleTextEditor {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        Stack stringBuilderStack = new Stack<>();
        while (N-- > 0) {

            int operation = in.nextInt();
            switch (operation) {
            case 1:
                StringBuilder top = (stringBuilderStack.isEmpty() ? new StringBuilder("") : stringBuilderStack.peek());
                StringBuilder newsb = new StringBuilder(top);
                newsb.append(in.next());
                stringBuilderStack.add(newsb);
                break;
            case 2:
                StringBuilder current = new StringBuilder(stringBuilderStack.peek());
                int start = current.length() - in.nextInt();
                int end = current.length();
                current.delete(start, end);
                stringBuilderStack.add(current);
                break;
            case 3:
                char toPrint = stringBuilderStack.peek().charAt(in.nextInt() - 1);
                System.out.println(toPrint);
                break;
            case 4:
                stringBuilderStack.pop();
                break;

            default:
                break;
            }
            // System.out.println(stringBuilderStack.peek().toString());
        }
        in.close();
    }
}
hackerrank :Simple Text Editor 简单文本编辑器_第2张图片
提交结果

你可能感兴趣的:(hackerrank :Simple Text Editor 简单文本编辑器)