Post

[Programmers] #120896 - 한 번만 등장한 문자 [Java][C++][Python]

[Programmers] #120896 - 한 번만 등장한 문자 [Java][C++][Python]

문제 링크


1. 아이디어

한 번만 등장하는 문자를 사전 순으로 이은 문자열을 구하는 문제다. 문자가 소문자 26종뿐이라 종류별로 등장 횟수를 센 뒤 횟수가 1인 문자를 사전 순으로 모으면 된다. a부터 z까지 순서대로 훑는 방식이라면 모은 문자가 이미 사전 순이라 따로 정렬하지 않아도 된다.


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 s) {
        int[] cnt = new int[26];
        for (char c : s.toCharArray()) {
            cnt[c - 'a']++;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 26; i++) {
            if (cnt[i] == 1) sb.append((char) (i + 'a'));
        }

        return sb.toString();
    }
}

i + 'a'는 int라 (char)로 바꿔야 문자로 붙는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

int cnt[26];

string solution(string s) {
    for (char c : s) cnt[c - 'a']++;

    string ans;
    for (int i = 0; i < 26; i++) {
        if (cnt[i] == 1) ans += i + 'a';
    }

    return ans;
}

i + 'a'는 int지만 std::string에 +=로 붙이면 char로 변환돼 문자로 덧붙는다.

1
2
3
4
5
6
from collections import Counter


def solution(s):
    cnt = Counter(s)
    return "".join(sorted(k for k, v in cnt.items() if v == 1))

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