코딩테스트 준비/백준

[백준 - 1283] - 단축키 지정(구현) C++

SeoburiFaust 2024. 3. 20. 23:48

문제

https://www.acmicpc.net/problem/1283

 

1283번: 단축키 지정

첫째 줄에 옵션의 개수 N(1 ≤ N ≤ 30)이 주어진다. 둘째 줄부터 N+1번째 줄까지 각 줄에 옵션을 나타내는 문자열이 입력되는데 하나의 옵션은 5개 이하의 단어로 표현되며, 각 단어 역시 10개 이하

www.acmicpc.net

접근방법

문자열 구현 문제였다.

 

검색안하고는 못 푸는 문제였다.

getline 함수 사용법, string 조작하는 법. 다 몰라서 검색해서 알아봤다.

 

사용법은 다음과 같다. 

getline으로 문자열 받는 법 : getline([inputstream], [string], [char])

-> inputstream으로 stdin을 치니까 안되고 cin치니까 됐다. 아마 header가 iostream이라서 그런 것 같다.

string 중간에 "[]"로 문자하나 감싸기 : c = c.substr(0, j) + "[" + string(1, c[j]) + "]" + c.substr(j+1)

-> string을 이용해 char를 string으로 변환했다. 파라미터에 숫자를 넣어서 길이를 정할 수 있다.

 

코드

int n;
vector<vector<string>> options;
bool visited[26] = {0,};
bool check_first(int i) {
    for(auto& c : options[i]) {      //각 옵션 마다 단어의 첫글자 검사
        int temp;
        if (c[0] < 'a') temp = c[0] - 'A';
        else temp = c[0] - 'a';
        if (!visited[temp]) {
            visited[temp] = 1;
            c = "[" + string(1, c[0]) + "]" + c.substr(1);
            return true;
        }
    }
    return false;
}
bool check_second(int i) {
    for(auto& c : options[i]) {      //각 옵션 마다 단어의 첫글자 검사
        for (int j = 1; j < c.size();j++) {
            int temp;
            if (c[j] < 'a') temp = c[j] - 'A';
            else temp = c[j] - 'a';
            if (!visited[temp]) {
                visited[temp] = 1;
                c = c.substr(0, j) + "[" + string(1, c[j]) + "]" + c.substr(j+1);
                return true;
            }
        }
    }
    return false;
}
int main() {
    cin >> n;
    getchar();
    options = vector<vector<string>>(n);
    FOR(i, n) {
        string line;
        getline(cin, line, '\n');
        stringstream ss(line);
        string token;
        while(getline(ss, token, ' ')) {
            options[i].push_back(token);
        }
    }
    FOR(i, n) {
        if (check_first(i)) continue;
        check_second(i);
    }
    for(auto option : options) {
        for (auto word : option) {
            cout << word << " ";
        }
        cout << endl;
    }
    return 0;
}

개선할 점

풀이시간을 좀 더 단축해보자.