프로그래머스 - 숫자 문자열과 영단어
본 알고리즘 풀이는 Routine Study에서 진행하고 있습니다.
저를 포함한 구성원이 대부분 초보이므로, 원하시는분은 언제라도 들어오셔도 좋습니다.
문의는 댓글 바람.
GitHub - ROUTINE-STUDY/Algorithm: 초보 알고리즘 스터디 / 누구나 참여 가능
초보 알고리즘 스터디 / 누구나 참여 가능 :runner:. Contribute to ROUTINE-STUDY/Algorithm development by creating an account on GitHub.
github.com
코딩테스트 연습 - 숫자 문자열과 영단어
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자
programmers.co.kr
[문제 설명]
영단어로 된 숫자를 정수로 바꿔라
[처음 생각한 접근 방법]
처음엔 one, two, three,..,nine까지 해서 앞자리가 중복이 없는지 확인했다. 근데 two three 둘다 t로 시작.
앞자리로 체크하는 방법은 안 될 듯.
그러던 와중에 전에 정규식 문제 풀이할 때 쓴 replaceAll 메서드가 생각났다.
1번 코드
class Solution {
public int solution(String s) {
int answer = 0;
s = s.replaceAll("zero","0");
s = s.replaceAll("one","1");
s = s.replaceAll("two","2");
s = s.replaceAll("three","3");
s = s.replaceAll("four","4");
s = s.replaceAll("five","5");
s = s.replaceAll("six","6");
s = s.replaceAll("seven","7");
s = s.replaceAll("eight","8");
s = s.replaceAll("nine","9");
return Integer.parseInt(s);
}
}
뭐 설명이 필요가 없는 코드. 그냥 무지성 replaceAll 해줬다.
2번 코드
import java.util.HashMap;
import java.util.Map;
class Solution {
public int solution(String s) {
int answer = 0;
Map<String, String> 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");
for (String key : map.keySet()) {
if (s.contains(key))
s = s.replaceAll(key, map.get(key));
}
return Integer.parseInt(s);
}
}
그냥 map에 담았다는 거 빼고 다를 게 없는 코드, 솔직히 의미 없는 코드다.
3번
enum Number {
zero, one, two, three,
four, five, six, seven,
eight, nine;
}
class Solution {
public int solution(String s) {
int answer = 0;
for (Number number : Number.values())
s = s.replaceAll(String.valueOf(number), String.valueOf(number.ordinal()));
return Integer.parseInt(s);
}
}
enum(열거형)을 활용한 풀이.
오 기발하다 생각하고 짰는데 막상 짜고 보니까 별로인 느낌.
처음엔 ordial을 몰라서 value를 따로 줬는데 인덱스를 구하는 ordial 메소드가 있는 걸 보고 써줬다.
알고리즘에 처음으로 열거형을 써보는 느낌이다.
코틀린 연습용 코드
class Solution {
fun solution(s: String): Int {
var string = s
val map = mapOf("zero" to "0", "one" to "1", "two" to "2", "three" to "3"
,"four" to "4", "five" to "5", "six" to "6"
,"seven" to "7", "eight" to "8", "nine" to "9"
)
for (entry in map) {
if (string.contains(entry.key))
string = string.replace(entry.key, entry.value)
}
return string.toInt()
}
}
이거 말고 s.replace().replace().replace()가 훨씬 나은 듯.
코틀린으로 맵을 안써봐서 코틀린 공부에 도움이 됐다는 점이 유일한 장점.