[프로그래머스/C++]Lv.0 - 옹알이 (1)

YH J·2023년 4월 20일
0

프로그래머스

목록 보기
65/168

문제 링크

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

시도한 방법

  1. 문자열에 모든 옹알이를 find한 다음 있으면 erase시킨 뒤 size가 0이면 answer++하는 방법 - "mayaa" aya를 먼저 검사한뒤 빼면 ma가 되서 ma도 되는거처럼되서 안되는 케이스인데 되는거로 되버림.
  2. 1을 수정해서 find하면 일단 다른 문자열 벡터에 저장해둔 뒤 find가 끝나면 그 후에 빼는 방법 - 케이스 2 8 10 14 15 16 오류
  3. (질문하기 참조) 문자열에서 find한 뒤 있으면 해당 옹알이 size만큼 int 변수에 + 하고 해당 옹알이부분을 공백이나 다른 문자로 대체함 대체시 1번시도의 문제를 해결 가능. 탐색이 전부 끝나고 원래 문자열size와 구한 size의 수치가 같다면 answer++
    -> 성공

내 코드

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

int solution(vector<string> babbling) {
    int answer = 0;
    vector<string> ongari = {"aya","ye","woo","ma"};
    for(const auto& b : babbling)
    {
        string s = b;
        int size = 0;
        for(const auto& o : ongari)
        {
            if(s.find(o) != string::npos)
            {
                size += o.size();
                s.replace(s.find(o), o.size()," ");
            }
        }
        if(b.size() == size)
           answer++;
    }  
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

int solution(vector<string> babbling) {
    int answer = 0;
    string temp = "";
    string temp2 = "";
    for(int i =0; i<babbling.size(); i++)
    {
        string s = babbling[i];
        temp = "";
        temp2 = "";
        for(int j=0; j<s.size(); j++)
        {
            temp += s[j];
            if(temp == "aya" || temp == "ye" || temp == "woo" || temp == "ma")
            {
                if(temp == temp2)
                    break;
                else
                    temp2 = temp;
                temp = "";
            }
        }
         if(temp == "")
                answer++;
    }
    return answer;
}

다른 사람의 풀이 해석

문자열의 처음부터 한글자씩 따오면서 옹알이랑 같은 단어일 경우 temp2에 저장해두고 temp는 초기화한다. 그 후 다른 옹알이가 나오면 temp2를 갱신하는데 temp2와 같은 단어가 나오면 ( 중복으로 나오면 ) 바로 break한다. 옹알이를 모두 검색해서 temp가 공백이면 answer을 ++한다.

profile
게임 개발자 지망생

0개의 댓글