[알고리즘] 프로그래머스_신규 아이디 추천

Fortice·2021년 6월 27일
0

알고리즘

목록 보기
9/18

본 블로그는 비상업적, 비영리적 용도의 학업만을 위해 글을 게시합니다.

1. 문제 분석

  • 주어진 조건과 단계에 맞춰 처리해주면 된다.

2. 문제 풀이 과정(삽질)

  • 라이브러리를 안쓰려고 C로만 짜는게 나름 삽질이다.
  • C++밖에 환경이 없지만, C문제를 보면 보통 배열이나 문자열의 길이는 줘서 string.length()는 그냥 쓰기로 했다.
  • 문제를 푸는 것에는 문제는 없었다.

3. 문제 해결

  • 각 단계를 따라 처리를 하지는 않았고, 적절히 들어갈 수 있는 것들을 넣는 식으로 짰다.
  • 조건문에 영어, 숫자, 빼기, 밑줄, 마침표 조건을 나열해서 하기 싫어서 bool형 check 배열을 만들어 문자를 인덱스로 해서 넣을 수 있는 것들을 true로 처리해줬다.
  • 마침표는 처음과 중복이면 무시한다.
  • 마침표가 끝에 있는 것 + 5단계 + 7단계는 마지막에 처리해줬다.

4. 코드

#include <string>
#include <vector>
#include <iostream>

using namespace std;

void init(bool check[])
{
    check[45] = true; // '-' == 45
    check[46] = true; // '.' == 46
    check[95] = true; // '_' == 95
    for(int i = '0'; i <= '9'; i++)
        check[i] = true;
    for(int i = 'A'; i <= 'Z'; i++)
    {
        check[i] = true;
        check[i + 32] = true;
    }
}

string solution(string new_id) {
    bool check[128] = {false};
    char ans[18] = {0};
    int ans_length = 0;
    
    init(check);
    
    for(int i = 0; i < new_id.length(); i++)
    {
        char now = new_id[i];
        //cout << now << " : " << check[now] << '\n';
        if(ans_length == 15)
            break;
        if(check[now])
        {
            if(now == '.')
            {
                if(ans_length != 0 && ans[ans_length - 1] != '.')
                    ans[ans_length++] = '.';
            }
            else if(now >= 'A' && now <= 'Z')
                ans[ans_length++] = now + 32;
            else
                ans[ans_length++] = now;
        }
    }
    
    if(ans_length > 0 && ans[ans_length - 1] == '.')
        ans[ans_length--] = 0;
    if(ans_length == 0)
        ans[ans_length++] = 'a';
    if(ans_length <= 2)
    {
        while(ans_length < 3)
        {
            ans[ans_length++] = ans[ans_length - 1];
        }
    }
    
    string answer(ans, ans_length);
    return answer;
}
profile
서버 공부합니다.

0개의 댓글