본문 바로가기
코딩 테스트/프로그래머스

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

by snow_hong 2022. 3. 21.
문제 설명
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다.
다음은 숫자의 일부 자릿수를 영단어로 바꾸는 예시입니다.
- 1478 → "one4seveneight"
- 234567 → "23four5six7"
- 10203 → "1zerotwozero3"

 

숫자
영단어
0
zero
1
one
2
two
3
three
4
four
5
five
6
six
7
seven
8
eight
9
nine

 


[ 나의 풀이 ]

import java.util.*;

class Solution {
    public int solution(String s) {
        int answer = 0;
        s = s.replaceAll("zero","0").replaceAll("one","1").replaceAll("two","2").replaceAll("three","3")
            .replaceAll("four","4").replaceAll("five","5").replaceAll("six","6").replaceAll("seven","7")
            .replaceAll("eight","8").replaceAll("nine","9");
        
        answer = Integer.parseInt(s); //string을 int형으로 변환
        
        return answer;
    }
}

[ 다른사람 풀이 ]

class Solution {
    public int solution(String s) {
        String[] strArr = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        for(int i = 0; i < strArr.length; i++) {
            s = s.replaceAll(strArr[i], Integer.toString(i));
        }
        return Integer.parseInt(s);
    }
}

나는 빠르게 풀 생각만하다가 노가다로 replaceAll처리를 다 해줬는데 다른사람의 코드를 보니 배열을 사용했다. 간결하면서 깔끔한 소스를 보고 코드를 쓰기전에 다시 한번 더 좋은 방법이 없는지 생각해보고 작성을 해보아야겠다고 생각이 들었다.

728x90

댓글