[프로그래머스/C++]Lv.1 - 문자열 나누기

YH J·2023년 5월 23일
0

프로그래머스

목록 보기
93/168

문제 링크

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

내 풀이

일단 first에 s[0]을 저장한다. num1은 1, num2는 0으로 시작한다.
first가 비어있을 경우 ( '0'을 넣어서 비어있음 처리함 ) s[i]를 넣어준다.
first와 s[i]가 같을 경우 num1++, 다를경우 num2++한 뒤 num1과 num2를 비교한다. 같을경우 answer++하고 초기화한다.
for문이 끝나고 나머지가 있는지 체크해서 있으면 answer++한다.

내 코드

#include <string>
#include <vector>

using namespace std;

int solution(string s) {
    int answer = 0;
    
    char first = s[0];
    int num1 = 1;
    int num2 = 0;
    
    for(int i = 1; i < s.length(); i++)
    {
        if(first == '0')
        {
            first = s[i];
            num1++;
            continue;
        }
        if(first == s[i])
            num1++;
        else
            num2++;
        if(num1 == num2)
        {
            answer++;
            num1 = 0;
            num2 = 0;
            first = '0';
        }
    }
    if(first != '0')
        answer++;
    
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

bool split(int& ind, const string& str)
{
    const char cur = str[ind];

    int countA = 1;
    int countB = 0;
    ind++;

    while(ind < str.size())
    {
        if(countA == countB)
        {
            return true;
        }

        if(cur == str[ind])
        {
            countA++;
        }
        else
        {
            countB++;
        }
        ind++;
    }

    return false;
}

int solution(string s) {
    int answer = 0;

    int ind = 0;    
    while(split(ind,s))
    {
        answer++;
    }

    return answer + 1;
}

다른 사람의 풀이 해석

함수를 만들어서 while을 돌렸다. 함수 진입 시 index기반으로 cur을 정해주고
countA와 countB가 같을 때 까지 while을 돌린다. 같으면 true를 리턴하고 끝까지 같은게 없으면 false를 리턴해서 while이 끝나게된다.

profile
게임 개발자 지망생

0개의 댓글