반응형

 

 

 

 

풀이코드

#include <string>
#include <vector>

using namespace std;

int GetTotElementSize(vector<string>);
int GetAnswer(string str);

int solution(string s) {
    int answer = GetAnswer(s);
    return answer;
}

int GetAnswer(string str)
{
    int resultSize = str.length();
    vector<string> resultVector;
    string currentStr, compareStr;

    for (int i = 1; i <= str.length() / 2; i++)
    {
        currentStr = str.substr(0, i);
        int compareCount = 1;
        int compareStart = i;

        while (compareStart < str.length())
        {
            compareStr = str.substr(compareStart, i);

            if (currentStr == compareStr)
            {
                compareCount++;
            }
            else
            {
                if (compareCount > 1)
                {
                    resultVector.push_back(to_string(compareCount));
                }
                resultVector.push_back(currentStr);

                currentStr = str.substr(compareStart, i);
                compareCount = 1;
            }
            compareStart += i;
        }

        if (compareCount > 1)
        {
            resultVector.push_back(to_string(compareCount));
        }
        resultVector.push_back(currentStr);

        int tot = GetTotElementSize(resultVector);
        resultSize = resultSize > tot ? tot : resultSize;
        resultVector.clear();
    }

    return resultSize;
}

int GetTotElementSize(vector<string> vecStr)
{
    int returnValue = 0;
    for(int i = 0; i < vecStr.size(); i++)
    {
        returnValue += vecStr[i].length();
    }
    return returnValue;
}
  • 문자열의 패턴을 비교해서 수를 메기는 형태이기 때문에 첫번째 반복문에서 모든 문자열길이만큼의 루프를 돌 필요가 없다.
  • while문의 각 루프마다 이전에 패턴 비교를 위해 잘라둔 문자열과 비교해서 같으면 compareCount를 증가시키고 다르면 비교 패턴을 수정해준다.

 

 

 

 

기타

- 잠깐 C++ 못했다고 레퍼런스가 기억이나지 않아서 비주얼스튜디오 켜서 작성함.

 

 

 

 

 

반응형

'Stack > Coding test' 카테고리의 다른 글

[C++ / Lv2] 전화번호 목록  (0) 2022.02.05
[C++ / Lv1] 완주하지 못한 선수  (0) 2022.02.04
[C# / Lv2] H-Index  (0) 2022.01.19
[C# / Lv2] 가장 큰 수  (0) 2022.01.18
[C# / Lv1] k번째 수  (0) 2022.01.17

+ Recent posts