[プログラマ]数字文字列とアルファベット語


回答日:2021-07-21

質問する


質問リンク:https://programmers.co.kr/learn/courses/30/lessons/81301

アクセスと解析


これは、ココア符号化テストでよく発生する文字列処理の問題です.
英語の単語(key)に対応する数字(value)をmapに保存し、数字が現れる前に文字列をチェックし、mapに格納された英語の単語が完了したら、英語の単語に一致するvalueを結果値に追加します.

コード#コード#

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

using namespace std;

int solution(string s) {
    map<string, int> m;
    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 ans = "";
    string str = "";
    for (auto c : s) {
        if (isdigit(c) == false) {
            str += c;
            if (m.find(str) != m.end()) {
                ans += to_string(m[str]);
                str = "";
            }
        } else {
            ans += c;
        }
    }
    
    int answer = stoi(ans);
    return answer;
}

結果



フィードバック


C++で問題を解くので、文字列を扱うためによく使われる様々な機能を身につけるべきです.