Post

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

문자열에서 정수 배열이 가리키는 인덱스의 글자를 지우고 남은 글자를 이어 붙이는 워밍업 문제.

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

문제 링크


1. 아이디어

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


2. 복잡도

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

($N$ = my_string의 길이)


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
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

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

    string s;
    for (char c : my_string) {
        if (c != '\0') s += c;
    }

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

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

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