알고리즘 풀이/프로그래머스

[프로그래머스][JAVA] 5주차_모음사전 (순열, 수학) #2

배게 2021. 10. 28. 21:26
728x90

#2 메모리↓↓

참고 : https://bangu4.tistory.com/241

참고 안보고는 이런 방식으로 못품 공백을 포함하기 때문에

unit[i] = unit[i+1]*5 +1이라는 공식을 도출을 못낼 것 같음...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public int solution(String word) {
        int answer = word.length();
        // char[] alp = new char[]{'A','E','I','O','U'};
        String alp = "AEIOU";
        int[] unit = new int[]{781,156,31,6,1};
        for(int i=0; i<word.length(); i++){
            answer += unit[i]*alp.indexOf(word.charAt(i));
        }
        
        
        return answer;
    }
}
cs

 

 

 

 

 

↓이거는 ... 사전 전부 등록한다음에 indexOf로 찾는 것이기 때문에 메모리 관리가 최악이나

내가 풀라고하면 이 방법밖에 안 떠오름..

다른 사람 풀이 보면 수학으로 풀고 어떻게 풀고 하는데

공통점은 단 하나의 단어에 대한 index를 찾는다는 것이다.

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
import java.util.*;
 
class Solution {
    Set<String> wordSet = new HashSet<>();
    StringBuilder sb = new StringBuilder();
    String[] alp = new String[]{"","A","E","I","O","U"};
    
    private void permutation(int pos){
        if(pos==5){
            wordSet.add(sb.toString());
            return ;
        }
        
        for(int i=0; i<alp.length; i++){
            sb.append(alp[i]);
            permutation(pos+1);
            if(i!=0)
                sb.deleteCharAt(sb.length()-1);
        }
    }
    
    public int solution(String word) {
        permutation(0);
        
        List<String> wordList = new ArrayList<>(wordSet);
        Collections.sort(wordList);
        // for(int i=0; i<10; i++){
        //     System.out.println(wordList.get(i));
        // }
        
        
        
        int answer = wordList.indexOf(word);
        return answer;
    }
}
cs