새발블로그

[프로그래머스/C++] 수 조작하기 1 본문

Problem Solving/Programmers

[프로그래머스/C++] 수 조작하기 1

EUG 2024. 3. 6. 18:17

문제

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

풀이방법

풀이 1

문제에서 요구하는 대로 함

 

풀이 2

STL map 사용

특정 문자에 대한 값이 변하지 않으니 맵을 사용해도 좋을 것 같아서 가져왔다.

 

MAP : 각 노드가 key 와  value 쌍으로 이루어진 트리로, 중복을 허용하지 않음

first와 second가 있는 pair 객체로 저장되면 first -key, second-value로 저장

c++ map의 내부 구현은 레드블랙트리라합니다.... O(logn)

 

map<key, value> 

특징

- 자료를 저장할 때 내부에서 자동으로 key를 중심으로 오름차순

- 내림차순 : map<int, int, greater> map이름

 

사용방법

- 헤더 : #include<map>

- 맵 선언 : map<key type, value type> 이름

- map 에서 데이터를 찾을 땐 iterator 사용 (m.find("key")

- 못찾으면 m.end() 반환~~

- 삽입 : map.insert({"key", 300});

- 반복문 접근 : m.begin()~ m.end()

- 삭제 : map.erase(특정 위치 인덱스)

- 삭제(요소) : map.erase("key")

- 모든 요소 삭제 : map.drease(map.begin(), map.end()); / map.clear();

 

 

풀이1

#include <string>
#include <vector>

using namespace std;

int solution(int n, string control) 
{
    for (char c : control)
    {
            if (c =='w') 
                n+=1;
            else if (c =='s') 
                n-=1;
            else if (c =='d') 
                n+=10;
            else if (c =='a') 
                n-=10;
    }
    int answer = n;
    return answer;
}

풀이2 (다른 사람풀이)

#include <string>
#include <vector>
#include <map>
using namespace std;

map <char, int> m = {{'w', 1}, {'s', -1}, {'d', 10}, {'a', -10}};
int solution(int n, string control) {
    int answer = n;
    for(char ch : control)
        answer += m[ch];
    return answer;
}