[문제] 옹알이(2)

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

내 풀이 (미완성)

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


// babbling_len은 배열 babbling의 길이입니다.
// 파라미터로 주어지는 문자열은 const로 주어집니다. 변경하려면 문자열을 복사해서 사용하세요.
int solution(const char* babbling[], size_t babbling_len) {
    int answer = 0;
    char* pronounciations[] = {"aya", "ye", "woo", "ma"}; 
    char* sound = "";
    char* temp = (char*)malloc(sizeof(char) * 10);
    for (size_t i = 0; i < babbling_len; ++i)
    {
        sound = babbling[i];
        
        while(babbling[i] != "\0")
        {
            strncat(temp, babbling[i], 1);
            for (int j = 0; j < 4; ++j)
            {
                if (temp.equal(pronounciations[j]))
                {
                    ++answer;
                    
                }
            }
        }
      
    }
    return answer;
}

 

풀이 과정

제시된 옹알이와 babblilng이 일치하는지 확인하기 위해서 babbling의 문자를 하나씩 뗀 다음 일치하는지 검사하는 방식으로 구현하려고 했다.

다만 strcmp와 같은 함수를 어떻게 쓰는지 까먹어서 길을 잃었다...

 

개선점

한 글자씩 떼어서 비교하는 로직 대신 옹알이와 일치하는 문자열 덩어리가 존재하는지 strcmp()로 한번에 비교하기. 

중복된 단어 두 개를 말할 수 없으므로 해당 부분 체크

 

개선된 코드 

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h> // 문자열 비교 함수 (strcmp, strlen)

int solution(const char* babbling[], size_t babbling_len)
{
	int answer = 0;
    
    for (size_t i = 0; i < babbling_len; ++i
    {
    	const char* word = babbling[i];
        bool isValid = true;
        int idx = 0;
        int lastSound = 0; // 인덱스로 방금 발음한 단어 기억
        int len = strlen(word); // 현재 문자열의 길이
        
        while(idx < len)
        {
        	if (strcmp(&word[idx], "aya", 3) == 0 && lastSound != 0) 
            {
            	idx += 3;
                lastSound = 0;
            }
            if (strcmp(&word[idx], "ye", 2) == 0 && lastSound != 1) 
            {
            	idx += 2;
                lastSound = 1;
            }
            if (strcmp(&word[idx], "woo", 3) == 0 && lastSound != 2) 
            {
            	idx += 3;
                lastSound = 2;
            }
            if (strcmp(&word[idx], "ma", 2) == 0 && lastSound != 3) 
            {
            	idx += 2;
                lastSound = 3;
            }
            else
            {
            	isValid = false;
                break; // 하나라도 일치하지 않을 시 -> 바로 빠져나옴
            }
        }
        
         if (IsValid && lastSound != )
        {
            answer++;
        }
    }
    
   return answer;
}

 

 

 

'C언어 공부 > 코드 테스트 연습' 카테고리의 다른 글

2026/7/24 코드카타  (1) 2026.07.24
2026/07/23 코드카타  (0) 2026.07.23

+ Recent posts