[HackerRank - Java] Day 6 - 1. Simple Text Editor

2023. 1. 29. 14:45Java/coding test

반응형

Simple Text Editor

Implement a simple text editor. The editor initially contains an empty string, SS. Perform QQ operations of the following 44 types:

  1. append(W) - Append string WW to the end of SS.
  2. delete(k) - Delete the last kk characters of SS.
  3. print(k) - Print the kthk^{th} character of SS.
  4. undo() - Undo the last (not previously undone) operation of type 11 or 22, reverting SS to the state it was in prior to that operation.

Example

S=abcdeS = 'abcde'
ops=[1fg,36,25,4,37,4,34]ops = ['1 fg', '3 6', '2 5', '4', '3 7', '4', '3 4']

operation
index   S       ops[index]  explanation
-----   ------  ----------  -----------
0       abcde   1 fg        append fg
1       abcdefg 3 6         print the 6th letter - f
2       abcdefg 2 5         delete the last 5 letters
3       ab      4           undo the last operation, index 2
4       abcdefg 3 7         print the 7th characgter - g
5       abcdefg 4           undo the last operation, index 0
6       abcde   3 4         print the 4th character - d

The results should be printed as:

f
g
d

Input Format

The first line contains an integer, QQ, denoting the number of operations.
Each line ii of the QQ subsequent lines (where 0<=i<Q0 <= i < Q) defines an operation to be performed. Each operation starts with a single integer, tt (where t1,2,3,4t ∈ {1, 2, 3, 4}), denoting a type of operation as defined in the Problem Statement above. If the operation requires an argument, tt is followed by its space-separated argument. For example, if t=1t = 1 and W="abcd"W = "abcd", line ii will be 1 abcd.

Constraints

  • 1<=Q<=1061 <= Q <= 10^6
  • 1<=k<=S1 <= k <= |S|
  • The sum of the lengths of all WW in the input <=106<= 10^6.
  • The sum of kk over all delete operations <=2106<= 2 * 10^6.
  • All input characters are lowercase English letters.
  • It is guaranteed that the sequence of operations given as input is possible to perform.

Output Format

Each operation of type 33 must print the kthk^{th} character on a new line.

Sample Input

STDIN   Function
-----   --------
8       Q = 8
1 abc   ops[0] = '1 abc'
3 3     ops[1] = '3 3'
2 3     ...
1 xy
3 2
4
4
3 1

Sample Output

c
y
a

Explanation

Initially, SS is empty. The following sequence of 88 operations are described below:

  1. S=""S = "". We append abcabc to SS, so S="abc"S = "abc".
  2. Print the 3rd3^{rd} character on a new line. Currently, the 3rd3^{rd} character is c.
  3. Delete the last 33 characters in S(abc)S(abc), so S=""S = "".
  4. Append xyxy to SS, so S="xy"S = "xy".
  5. Print the 2nd2^{nd} character on a new line. Currently, the 2nd2^{nd} character is y.
  6. Undo the last update to SS, making SS empty again (i.e., S=""S = "").
  7. Undo the next to last update to SS (the deletion of the last characters), making S="abc"S = "abc".
  8. Print the 1th1^{th} character on a new line. Currently, the 1th1^{th} character is a.

간단한 텍스트 에디터를 구현하세요.
에디터는 빈문자열인 S로 초기화 되어있고, Q번 동작을 합니다.
동작의 종류는 총 4가지로 각각 숫자로 행할 수 있습니다.

  1. append(W): S 문자열 끝에 "W" 문자열 추가
  2. delete(k): S 문자열의 끝에서 k개 문자 제거
  3. print(k): k번째 인덱스에 있는 문자 출력
  4. undo(): (undo, print를 제외한) 맨마지막에 실행했던 행위로 되돌리기

맨 첫줄은 operation 수를 담는 Q
그 후엔 각각 동작에 대한 입력

undo를 구현하기 위해 stack을 사용하면 됩니다.

public class SimpleTextEditorExample {

    private static final Scanner scanner = new Scanner(System.in);
    private static final Stack<String> stack = new Stack<>();

    public static void main(String[] args) {
        int Q = scanner.nextInt();
        stack.push("");
        while (Q > 0) {
            int ops = scanner.nextInt();
            switch (ops) {
                case 1:
                    append(scanner.next());
                    break;
                case 2:
                    delete(scanner.nextInt());
                    break;
                case 3:
                    print(scanner.nextInt());
                    break;
                default:
                    undo();
            }
            Q--;
        }
    }

    static void append(String W) {
        stack.push(stack.peek() + W);
    }

    static void delete(int k) {
        String newStr = stack.peek();
        newStr = newStr.substring(0, newStr.length() - k);
        stack.push(newStr);
    }

    static void print(int k) {
        System.out.println(stack.peek().charAt(k - 1));
    }
    static void undo() {
        stack.pop();
    }

}

append할 때, stack에 이전 문자열에 W를 더한 것을 넣어주면 됩니다.

charAt은 i번째 인덱스에 있는 문자를 리턴하는 함수입니다.
k는 1부터 시작되기 떄문에 1을 빼줘야 합니다.

Q가 최대 10610^6 번 행해질 수 있기 때문에 불필요한 연산이 많을 경우, timeout에러가 발생되어,
peek연산 이전에 stack이 empty가 아닌지 체크하는 부분은 제외했습니다.

728x90
반응형