[프로그래머스/C++]Lv.0 - 모스부호 (1)

YH J·2023년 4월 19일
0

프로그래머스

목록 보기
56/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/120838

내 풀이

모스부호를 모두 맵에 넣고 stringstream으로 파싱해가면서 맞는 단어를 완성한다.
m.find(temp)->second 이거 말고 m[temp]를 하면 더 간결할 것 같다. while의 조건을 잘 생각하면서 하자. s>>temp나 while(s)도 가능

내 코드

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

using namespace std;

string solution(string letter) {
    string answer = "";
    map<string,string> m =
    {
        {".-","a"},{"-...","b"},{"-.-.","c"},{"-..","d"},
        {".","e"},{"..-.","f"},{"--.","g"},{"....","h"},
        {"..","i"},{".---","j"},{"-.-","k"},{".-..","l"},
        {"--","m"},{"-.","n"},{"---","o"},{".--.","p"},
        {"--.-","q"},{".-.","r"},{"...","s"},{"-","t"},
        {"..-","u"},{"...-","v"},{".--","w"},{"-..-","x"},
        {"-.--","y"},{"--..","z"}
    };
    
    stringstream s;
    s.str(letter);
    string temp;
    while(s>>temp)
    {
        answer += m.find(temp)->second;
    }
    
    return answer;
}

다른 사람의 풀이

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

using namespace std;

map<string,char> m = {
    {".-",'a'},{"-...",'b'},{"-.-.",'c'},{"-..",'d'},
    {".",'e'},{"..-.",'f'},{"--.",'g'},{"....",'h'},
    {"..",'i'},{".---",'j'},{"-.-",'k'},{".-..",'l'},
    {"--",'m'},{"-.",'n'},{"---",'o'},{".--.",'p'},
    {"--.-",'q'},{".-.",'r'},{"...",'s'},{"-",'t'},
    {"..-",'u'},{"...-",'v'},{".--",'w'},{"-..-",'x'},
    {"-.--",'y'},{"--..",'z'}
};

string solution(string letter) {
    string answer = "";
    stringstream ss(letter);
    string s;

    while (!ss.eof()) {
        ss >> s;
        auto t = m.find(s);
        if(t != m.end()) {
            answer += t->second;
        }
    }
    return answer;
}

다른 사람의 풀이 해석

eof (end of file) 더이상 읽을게 없는지 체크

profile
게임 개발자 지망생

0개의 댓글