Post

[프로그래머스/LV1] [PCCP 모의고사 1] 1번 - 문자열, 구현 (Java)

프로그래머스 LV1 [PCCP 모의고사 1] 1번 문제를 Java로 해결한 풀이입니다. 문자열, 구현 알고리즘을 활용하여 규칙을 나누어 문제를 정의합니다.

[programmers-lv1] [PCCP 모의고사 1] 1번

🙋‍♂️ 들어가며

조금 헤맸으나, 맨 첫 문자를 압축문자에 추가하고 압축문자에는 현재문자가 이전문자와 같지 않을때만 더해주면 된다.

그리고 압축문자에서 알파벳 사전을 생성해 전부 더해주고,

마지막에 2회 이상인 것만 합쳐서 출력하면 된다.

만약 answer 길이가 1미만이면 “N” 반환


✅ 정답 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
    public String solution(String input_string) {
        String answer = "";
        
        // 1. 압축 문자열 (첫글자는 미리 넣어두기)
        String compressed = "";
        compressed += input_string.charAt(0);
        
        // 2. 이전 문자열과 같으면 추가 안한다.
        int N = input_string.length();
        for (int i = 1; i < N; i++) {
            char cur_ch = input_string.charAt(i);
            char prev_ch = input_string.charAt(i-1);
            
            if (cur_ch == prev_ch) continue;
            compressed += cur_ch;
        }
        
        // 3. dict 생성
        int[] dict = new int[26];
        for (int i = 0; i < compressed.length(); i++) {
            char cur_ch = compressed.charAt(i);
            dict[cur_ch - 'a']++;
        }
        
        // 4. dict에서 2개 넘는거면 answer에 추가
        for (int i = 0; i < 26; i++) {
            if (dict[i] >= 2) {
                answer += (char) (i + 'a');
            }
        }
        
        // 5. 출력 (아무것도 없다면)
        if (answer.length() < 1) {
            return "N";
        }
        
        // 6. 그외 출력
        
        return answer;
    }
}
This post is licensed under CC BY 4.0 by the author.

Trending Tags