코딩테스트/프로그래머스 - LV 0
[프로그래머스] 모스부호(1)
웅드
2024. 1. 5. 16:14
- 내 풀이
#include <string>
#include <vector>
#include <map>
using namespace std;
map<string,char> mos = {
{".-",'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 = "";
string index = "";
vector<string> s;
for(int i = 0; i < letter.size(); i++){
if(letter[i]==' '){
s.push_back(index);
index="";
}
else{
index += letter[i];
}
}
s.push_back(index);
for(int i=0; i< s.size(); i++){
if(mos.find(s[i])!= mos.end()){
answer += (char)mos[s[i]];
}
}
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;
}
stringstream은 주어진 문자열에서 필요한 자료형에 맞는 정보를 꺼낼 때 사용된다,
공백과 '\n'을 제외하고 문자열에서 맞는 자료형의 정보를 빼주기 때문에 stringstream을 사용한 것 같다.
반응형