알고리즘
[프로그래머스] [C#] 숫자 문자열과 영단어
HyoSeong
2021. 8. 2. 00:38
반응형
안녕하세요.
오늘은 프로그래머스 코딩테스트 연습 문제인 "숫자 문자열과 영단어" 을 풀어 보았습니다.
문제 링크
https://programmers.co.kr/learn/courses/30/lessons/81301
문제 풀이 방법
대응되는 영단어와 숫자를 Dictionary에 넣고, Dictionary를 돌며 Replace를 해줍니다.
C#에서의 Replace함수는 내부적으로 c++로 구현 되어있기 때문에 빠른 속도로 문자열을 교체해줍니다.
https://stackoverflow.com/questions/39403992/decompile-net-replace-method-v4-6-1
https://github.com/g15ecb/shared-source-cli-2.0/blob/master/clr/src/vm/comstring.cpp#L1572
이러한 방법을 사용하여 저는 문제를 풀었고,
이번 문제는 평균 약 1.40ms 정도의 속도로 테스트를 통과하였습니다.
코드
using System;
using System.Collections.Generic;
public class Solution {
public int solution(string s) {
Dictionary<string, string> numberDictionary = new Dictionary<string, string>()
{
{ "zero", "0" },
{ "one", "1" },
{ "two", "2" },
{ "three", "3" },
{ "four", "4" },
{ "five", "5" },
{ "six", "6" },
{ "seven", "7" },
{ "eight", "8" },
{ "nine", "9" }
};
foreach (var keyValuePair in numberDictionary)
{
s = s.Replace(keyValuePair.Key, keyValuePair.Value);
}
return Int32.Parse(s);
}
}
반응형