반응형
Recent Posts
Notice
Recent Comments
Link
250x250
«   2025/05   »
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
Archives
Today
Total
관리 메뉴

지식창고

[Java] 프로그래머스 PCCP 실전모의고사 - 외톨이 알파벳 본문

Algorithm/Programmers

[Java] 프로그래머스 PCCP 실전모의고사 - 외톨이 알파벳

junz 2023. 10. 27. 15:31
728x90
반응형

[Java] 프로그래머스 PCCP 실전모의고사 - 외톨이 알파벳

 

 

문   제 : 

알파벳 소문자로만 이루어진 어떤 문자열에서, 2회 이상 나타난 알파벳이 2개 이상의 부분으로 나뉘어 있으면 외톨이 알파벳이라고 정의합니다.

문자열 "edeaaabbccd"를 예시로 들어보면,

a는 2회 이상 나타나지만, 하나의 덩어리로 뭉쳐있으므로 외톨이 알파벳이 아닙니다.

"ede(aaa)bbccd"

b, c도 a와 같은 이유로 외톨이 알파벳이 아닙니다.

d는 2회 나타나면서, 2개의 부분으로 나뉘어 있으므로 외톨이 알파벳입니다.

"e(d)eaaabbcc(d)"

e도 d와 같은 이유로 외톨이 알파벳입니다.

문자열 "eeddee"를 예시로 들어보면,

e는 4회 나타나면서, 2개의 부분으로 나뉘어 있으므로 외톨이 알파벳입니다.

"(ee)dd(ee)"

d는 2회 나타나지만, 하나의 덩어리로 뭉쳐있으므로 외톨이 알파벳이 아닙니다.

"ee(dd)ee"

문자열 input_string이 주어졌을 때, 외톨이 알파벳들을 알파벳순으로 이어 붙인 문자열을 return 하도록 solution 함수를 완성해주세요. 
만약, 외톨이 알파벳이 없다면 문자열 "N"을 return 합니다.

 

제한사항(Constraint)
  • 1 ≤ input_string의 길이 ≤ 2,600
  • input_string은 알파벳 소문자로만 구성되어 있습니다.

 

 

Example )

Input : "edeaaabbccd"
Output : "de"

Input : "eeddee"
Output : "e"

Input : "string"
Output : "N"

Input : "zbzbz"
Output : "bz"


접   근 : 


각 알파벳이 몇 번 나오는지 세고, 2회 이상 나타난 애들에 한해서, 
2개 이상의 부분으로 나뉘어 있는가를 체크 -> 인덱스가 이어져있는가? -> 아니면 외톨이 알파벳

 

 


결   과  :

import java.util.*;
class Solution {
    public String solution(String input_string) {
        int[] dic = new int[26];
        List<List<Integer>> indexList = new ArrayList<>();
        StringBuilder result = new StringBuilder();
        // a = 97 ascii
        // 각 알파벳이 몇 번 나오는지 세고, 2회 이상 나타난 애들에 한해서, 
        // 2개 이상의 부분으로 나뉘어 있는가를 체크 -> 인덱스가 이어져있는가? -> 아니면 외톨이
        
        for(int i=0; i<26; i++){
            indexList.add(new ArrayList<>());
        }
        
        for(int i=0; i<input_string.length(); i++){
            char c = input_string.charAt(i);
            int idx = c - 'a';
            dic[idx]++;
            indexList.get(idx).add(i);
        }
        System.out.println(indexList);
        
        for(int i=0; i<dic.length; i++){
            if(dic[i] < 2) {
                continue;
            }
            // 인덱스가 이어져있는가 체크
            if(!isCombo(indexList.get(i))) {
                char alone = (char)('a' + i);
                result.append(Character.toString(alone));
            }
        }
        return result.length()==0 ? "N" : result.toString();
    }
    public boolean isCombo(List<Integer> num) {
        int start = num.get(0);
        for(int i=1; i<num.size(); i++) {
            if(start+1 != num.get(i)) {
                return false;
            }
            start++;
        }
        return true;
    }
}
728x90
반응형
Comments