[프로그래머스 스쿨Lv0] 코드 처리하기

2023. 8. 2. 21:31코딩테스트/프로그래머스 스쿨 - LEVEL0

[문제]

 

프로그래머스

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

programmers.co.kr

[주의할 점]

단일 문자를 비교할 때는, 직접 대입 연산을 활용해야 한다.
answer[a++]=code[i];
단일 문자를 직접 입력할 때는, 작은 따옴표를 사용해야 한다.
if(code[i] == "1") (x)
if(code[i] == '1') (o)

[코드]

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
char* solution(const char* code) {
    int len = strlen(code);
    int flag = 0, a = 0; //여기서 a는 answer의 idx
    char* answer = (char*)malloc(len+1); //처음에 길이를 최대로 부여했기 때문에 마지막에 '\0'을 넣어줘야 한다.
    
    for(int i=0;i<len;i++){
        if(code[i]=='1'){
            if(flag==1)
                flag=0;
            else if(flag==0)
                flag=1;
            i++;
        }
        if(i>=len) //초과하면
            break;
        
        if(flag==0){
            while(code[i]!='1'){
                if(i%2==0)
                    answer[a++]=code[i];
                i++;
                if(i>=strlen(code)) //초과하면
                    break;
            }
        }else if(flag==1){
            while(code[i]!='1'){
                if(i%2!=0)
                    answer[a++]=code[i];
                i++;
                if(i>=strlen(code)) //초과하면
                    break;
            }
        }
        i--; //i++이 후에 실행되면 i+=2인 것이므로 i-=1을 해준다
    }
    
    
    if(a==0) //answer이 비어있으면
        strcpy(answer,"EMPTY");
    else //비어있지 않으면 마지막에 '\0'을 넣어라
        answer[a]='\0';
    
    return answer;
}