Post

[Programmers] #181870 - ad 제거하기 [Java][C++][Python]

[Programmers] #181870 - ad 제거하기 [Java][C++][Python]

문제 링크


1. 아이디어

문자열 배열 strArr에서 "ad"를 부분 문자열로 포함하는 문자열을 제거한 후 반환하는 문제로 문자열이 부분 문자열로 포함됐는지 판단하는 내장 기능을 활용하면 간단하게 해결할 수 있다.


2. 복잡도

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

($N$ = strArr의 길이, $M$ = 각 문자열의 길이. 공간은 Java·Python이 필터링된 문자열의 참조만 새 리스트에 담아 $O(N)$이고, C++는 push_back이 문자열 내용을 복사하므로 $O(N \times M)$)


3. 코드

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

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;

class Solution {
    public String[] solution(String[] strArr) {
        List<String> list = new ArrayList<>();
        for (String s : strArr) {
            if (s.contains("ad")) continue;
            list.add(s);
        }

        return list.toArray(new String[0]);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;

vector<string> solution(vector<string> strArr) {
    vector<string> v;
    for (string& s : strArr) {
        if (s.find("ad") != -1) continue;
        v.push_back(s);
    }

    return v;
}
1
2
def solution(strArr):
    return [s for s in strArr if "ad" not in s]

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