알고리즘/프로그래머스 1단계

프로그래머스 - 중복된 문자 제거 - C++

게임만드는학생 2023. 8. 30. 16:33

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

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

using namespace std;

string solution(string my_string) {
    string answer = "";
    map<char,bool> m;
    
    for(int i=0;i<my_string.length();i++)
    {
        if(m.find(my_string[i])==m.end())
        {
            answer+=my_string[i];
            m.insert({my_string[i],true});
        }
    }
    
    return answer;
}

 

설명

my_string 에서 중복되는 문자들을 삭제하는 건데, map을 이용하면 쉽게 해결할 수 있다.

 map 은 <key, value> 의 자료구조를 가지고 있다. 

그리고 key 값을 통해 map 자료구조에 key가 있는지를 빠르게 확인할 수 있다. 

따라서 for문으로 my_string의 문자를 1개씩 map에서 찾아보고 있으면 넘기고 없으면 map에 추가한 후,

answer 문자열에 추가하면 된다. 

 

//  my_string[i]가 없으면 m.find 함수가 m.end() 를 반환한다.
if(m.find(my_string[i])==m.end())