본문 바로가기

카테고리 없음

[PGS] 프로그래머스 - 모음사전 (JAVA)

https://school.programmers.co.kr/learn/courses/30/lessons/84512

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

import java.util.*;
import java.io.*;

class Solution {
    
    static String tmp="";
    static String[] alph = {"A","E","I","O","U"};
    static ArrayList<String> voca = new ArrayList<>();
    static void getWord(int n, int k){
        if(n==k){
            voca.add(tmp);
            return;
        }
        for(int i=0;i<5;i++){
            tmp += alph[i];
            getWord(n,k+1);
            tmp = tmp.substring(0,tmp.length()-1);
        }
        
    }
    public int solution(String word) {
        int answer = 0;
       
        //중복순열
        for(int i=1;i<=5;i++){
            getWord(i,0);
        }
        
        String[] tmpVoca = new String[voca.size()];
        for(int i=0;i<voca.size();i++){
            tmpVoca[i] = voca.get(i);
        }
        
        Arrays.sort(tmpVoca);
        
        for(int i=0;i<tmpVoca.length;i++){
            if(tmpVoca[i].equals(word)){
                answer = i+1;
            }
        }
        return answer;
    }
}

1. 단어를 만들어서 정렬해둔다.

2. 정렬된 단어장에서 주어진 단어의 순서를 찾아 return 한다.

나는 위 코드로 사전에 들어갈 단어를 만들었는데 서치를 하다가 아래 방법도 찾았다.

list 정렬을 몰랐는데,, Collections.sort()로 하면 된다니 ...ㅜㅜ...

import java.util.ArrayList;
import java.util.Collections;
class Solution {
    static char[] alphabet= {'A','E','I','O','U'};
    static ArrayList<String> list;
    
    public int solution(String word) {
        list= new ArrayList<>();
        int answer = 0;
        
        combination(0, "");
        Collections.sort(list);
        answer= list.indexOf(word)+1;
        
        return answer;
    }
    
    public void combination(int index, String str){
        if(index>=5) return;
        for(int i=0; i<alphabet.length; i++){
            list.add(str+alphabet[i]);
            combination(index+1, str+alphabet[i]);
        }
    }//comb
}