[Programmers] #181900 - 글자 지우기 [Java][C++][Python]
[Programmers] #181900 - 글자 지우기 [Java][C++][Python]
1. 아이디어
글자를 하나씩 지우면 뒤 글자들의 인덱스가 앞으로 당겨져 indices가 가리키는 위치가 어긋난다. 그래서 지울 위치를 먼저 전부 표시해 두고, 표시되지 않은 글자만 이어 붙인다. my_string이 영소문자뿐이라 널 문자를 표시로 써도 원래 글자와 겹치지 않는다.
2. 코드
풀이 [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;
}
표시해 둔 널 문자를 std::erase로 한꺼번에 지웠다. 이 함수는 C++20부터 쓸 수 있다.
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.