Post

[Programmers] #181900 - 글자 지우기 [Java][C++][Python]

[Programmers] #181900 - 글자 지우기 [Java][C++][Python]

문제 링크


1. 아이디어

indices에 담긴 각 인덱스 위치의 글자를 지울 대상으로 표시한 뒤, 문자열을 앞에서부터 순회하며 표시되지 않은 글자만 이어 붙이면 된다. my_string이 영소문자로만 이루어져 있으므로 널 문자를 지움 표시 값으로 덮어써도 원래 글자와 충돌하지 않는다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(N)$

($N$ = my_string의 길이. C++는 인자 문자열을 제자리에서 지운 뒤 반환해 공간 $O(1)$)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
    public String solution(String my_string, int[] indices) {
        char[] arr = my_string.toCharArray();
        for (int i : indices) {
            arr[i] = '\u0000';
        }

        StringBuilder sb = new StringBuilder();
        for (char c : arr) {
            if (c != '\u0000') sb.append(c);
        }

        return sb.toString();
    }
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

string solution(string my_string, vector<int> indices) {
    for (int i : indices) {
        my_string[i] = '\0';
    }
    erase(my_string, '\0');

    return my_string;
}
1
2
3
4
5
6
def solution(my_string, indices):
    s = list(my_string)
    for i in indices:
        s[i] = "\0"

    return "".join(c for c in s if c != "\0")

This post is licensed under CC BY 4.0 by the author.