학습(0)/C++ 문제풀이

중복 문자 제거/string::find

누가 뭐래도 개발자 2025. 3. 11. 20:13
  • 내 코드

중복만 생각하고 set썼다가 순서를 유지하지 못해서 그냥 answer 중복 검사를 했다.

string.find는 반환값이 int이고,  못 찾을 경우 end()가 아닌 string::npos(-1)이다. 

 

#include <string>
#include <vector>

using namespace std;

string solution(string my_string) {
    string answer = "";

    for (char c : my_string)
    {
        if (string::npos == answer.find(c))
        {
            answer += c;
        }
    }

    return answer;
}

 

  • 개선

set을 같이 사용해서 중복 검사에만 set을 이용한다.

탐색에 O(1) 이기에 총 시간 복잡도는 O(N)이 된다!

 

#include <string>
#include <vector>
#include <unordered_set>

using namespace std;

string solution(string my_string) {
    string answer = "";
    unordered_set<char> seen;

    for (char c : my_string) {
        if (seen.find(c) == seen.end()) {
            answer += c;
            seen.insert(c);
        }
    }

    return answer;
}

'학습(0) > C++ 문제풀이' 카테고리의 다른 글

최댓값 2/ 조합 연습  (0) 2025.03.12
세균증식/ 2와 관련 된 건 비트 연산  (0) 2025.03.11
소인수분해  (0) 2025.03.11
문자열 정렬/ isdigit()/ reserve()  (0) 2025.03.11
모음 제거/ remove_if  (0) 2025.03.11