Post

[Programmers] #120956 - 옹알이 (1) [Java][C++][Python]

[Programmers] #120956 - 옹알이 (1) [Java][C++][Python]

문제 링크


1. 아이디어

문자열 배열 babbling에서 조카가 발음할 수 있는 단어의 개수를 구하는 문제로 "aya", "ye", "woo", "ma" 4가지 단어로만 이루어져 있어야 발음할 수 있는 단어다. 각 단어별로 위 4개에 해당하는 패턴을 공백으로 치환한 후 단어가 전부 공백으로 이루어져 있는지 비교하는 방식으로 해결했다.


2. 복잡도

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

($N$ = babbling의 길이, $M$ = babbling 원소 문자열의 길이. C++는 원소 문자열을 제자리에서 치환하므로 공간 $O(1)$)


3. 코드

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public int solution(String[] babbling) {
        int cnt = 0;
        for (String s : babbling) {
            String res = s
                    .replace("aya", " ")
                    .replace("ye", " ")
                    .replace("woo", " ")
                    .replace("ma", " ");

            if (res.isBlank()) cnt++;
        }

        return cnt;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

int solution(vector<string> babbling) {
    int cnt = 0;
    for (string& s : babbling) {
        for (string p : {"aya", "ye", "woo", "ma"}) {
            int pos = s.find(p);
            if (pos != -1) s.replace(pos, p.size(), " ");
        }

        bool ok = true;
        for (char c : s) {
            if (!isspace(c)) ok = false;
        }
        if (ok) cnt++;
    }

    return cnt;
}
1
2
3
4
5
6
7
8
9
10
def solution(babbling):
    cnt = 0
    for s in babbling:
        for pat in ("aya", "ye", "woo", "ma"):
            s = s.replace(pat, " ")

        if not s.strip():
            cnt += 1

    return cnt

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