숫자 문자열과 영단어

jiholee·2021년 11월 24일
0

알고리즘

목록 보기
4/20

숫자 문자열과 영단어

#include <string>
#include <vector>
#include <map>

using namespace std;
map<string, string> m;

int solution(string s) {
    int answer = 0;

    m["zero"] = "0";
    m["one"] = "1";
    m["two"] = "2";
    m["three"] = "3";
    m["four"] = "4";
    m["five"] = "5";
    m["six"] = "6";
    m["seven"] = "7";
    m["eight"] = "8";
    m["nine"] = "9";
    
    string cur = "";
    string res = "";
    for(int i = 0; i < s.length(); i++)
    {
        if(isdigit(s[i]) == 0)   // ⭐️
        {
            cur += s[i];
            if(m.find(cur) != m.end())  // ⭐️
            {
                res += m[cur];
                cur = "";
            }
        }
        else 
            res += s[i];
    }

    answer = stoi(res);
    return answer;
}

isdigit(), map find(key) 함수를 잘 활용하자


python 풀이

enumerate또는 딕셔너리를 이용해서 간단하게 할 수 있다.

딕셔너리 설명: https://wikidocs.net/16


  • enumerate 이용
def solution(s):
    table = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    
    for index, value in enumerate(table):
        if value in s:
            s = s.replace(value, str(index))
        
    
    return int(s)

  • 딕셔너리 이용
def solution(s):
    table = {"zero":"0", "one":"1", "two":2, "three":3, "four":4, "five":5, "six":6, "seven":7, "eight":8, "nine":9}
    
    for key, value in table.items():   # ⭐️
        if key in s:
            s = s.replace(key, str(value))
        
    
    return int(s)

0개의 댓글