ALGORITHM/PROGRAMMERS

[프로그래머스] 숫자 문자열과 영단어 (2021 카카오 채용연계형 인턴십)

0298 2021. 7. 15. 20:51

https://programmers.co.kr/learn/courses/30/lessons/81301

 

코딩테스트 연습 - 숫자 문자열과 영단어

네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자

programmers.co.kr

2021-07-15


1) replaceAll

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
    public int solution(String s) {
        int answer = 0;
        String[] alpha = {"zero""one""two""three""four""five""six""seven""eight""nine"};
 
        for(int i = 0; i < alpha.length; i++) {
            s = s.replaceAll(alpha[i], String.valueOf(i));
        }
        answer = Integer.parseInt(s);
        return answer;
    }
}
cs

2) one by one

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.HashMap;
import java.util.Map;
 
public class Solution81301 {
    public static int solution(String s) {
        int answer = 0;
        Map<String, Integer> map = new HashMap<>();
        map.put("zero"0);
        map.put("one"1);
        map.put("two"2);
        map.put("three"3);
        map.put("four"4);
        map.put("five"5);
        map.put("six"6);
        map.put("seven"7);
        map.put("eight"8);
        map.put("nine"9);
 
        String ans = "";
        String tmp = "";
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if('0' <= ch && ch <= '9') {
                ans += String.valueOf(ch);
            } else {
                tmp += s.charAt(i);
                if(!tmp.equals(""&& map.containsKey(tmp)) {
                    ans += String.valueOf(map.get(tmp));
                    tmp = "";
                }
            }
        }
        answer = Integer.parseInt(ans);
        return answer;
    }
}
cs

 

#문제풀이

처음에는 글자 하나씩 체크해서 단어를 찾는 방법으로 풀었다.

 

뭔가 더 좋은 방법이 있을 것 같아서 다른 사람의 풀이를 참고 해봤고, replaceAll이라는 것을 쓴 것을 확인해서, 그 방법으로 다시 풀어봤다.