그럴듯한 개발 블로그
반응형

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

 

프로그래머스

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

programmers.co.kr

역시 카카오 문제는 골아프다.

처음에 테스트케이스랑 문제 제대로 안 살펴보고 풀다가 피봤다...

스트링을 끝까지 보면서 콤마의 개수가 가장 많은 수 묶음의 시작 인덱스를 찾아서 ,로 나눠서 stoi해줘서 벡터에 넣어줬다.

#include <string> // 실패 코드
#include <vector>
#include <iostream>

using namespace std;

int getCommaCnt(int *i, string s) // 괄호가 닫히기 전 까지 돌면서 콤마의 개수 리턴
{
    int cnt = 0;
    
    while (s[*i] != '}')
    {
        if (s[*i] == ',')
            cnt++;
        (*i)++;
    }
    return (cnt);
}

int getNumLen(int i, string s) // 현재 튜플안의 숫자의 길이 리턴
{
    int res = 0;
    while (s[i + res] != ',' && s[i + res] != '}')
        res++;
    return (res);
}

vector<int> solution(string s) {
    vector<int> answer;
    int i = 2, commaCnt = -1, startIdxCommaCnt = -1;
    
    while (i < s.size())
    {
        int curI = i; // 현재 튜플의 첫번째 인자 인덱스
        int curCommaCnt = getCommaCnt(&i, s); // 현재 튜플의 콤마의 개수
        if (commaCnt < curCommaCnt) // 이번 튜플이 더 많이 들어있으면 갱신
        {
            startIdxCommaCnt = curI;
            commaCnt = curCommaCnt;
        }
        i += 3; // 닫는 괄호 가리키고 있으므로 다음 튜플의 처음 인자 가리키게 옮겨줌
    }
    for (int i = startIdxCommaCnt; s[i] != '}'; i++)
        cout << s[i];
    cout << '\n';
    // for (i = startIdxCommaCnt; i < s.size() && s[i] != '}'; i++)
    // {
    //     int numLen = getNumLen(i, s);
    //     answer.push_back(stoi(s.substr(i, numLen)));
    //     i += numLen;
    // } // 에러처리하다가 테케 잘못 본거 보고 갈아 엎음...
    return answer;
}

 

"{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

하지만 이 코드는 이 테케에서 제일 긴 숫자묶음을 그대로 벡터에 pushback해주므로 2 3 4 1이 들어가게 된다. 바로 갈아엎어줬다.

 

두번째 뻘짓 코드..

{를 구분자로 스플릿으로 잘라줬다. 그러면 

2},
2,1},
2,1,3},
2,1,3,4}}

이런식으로 잘리게 된다. 아하! sort하고 순서대로 하나씩 벡터에 넣어주면 되겠다!

#include <string> <실패코드2>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

vector<string>	ft_split(string s, char sep) // 구분자 하나짜리
{
	vector<string>	res;
	int	start_idx = 0;

	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] == sep)
		{
			if (i > start_idx)
				res.push_back(s.substr(start_idx, i - start_idx));
			start_idx = i + 1;
		}
	}
		if (start_idx < s.size())
			res.push_back(s.substr(start_idx, s.size() - start_idx));
	return (res);
}

bool    cmp(string a, string b)
{
    return (a.size() < b.size());
}

int getNumLen(int i, string s) // 현재 튜플안의 숫자의 길이 리턴
{
    int res = 0;
    while (s[i + res] != ',' && s[i + res] != '}')
        res++;
    return (res);
}

vector<int> solution(string s) {
    vector<int>     answer;
    vector<string>  split = ft_split(s, '{'); // "숫자, 숫자, 숫자}," 이런식으로 잘리게 된다.
    int             idxTuple = 0;
    
    sort(split.begin(), split.end(), cmp);
    for (int i = 0; i < split.size(); i++)
        cout << split[i] << '\n';
    for (int i = 0; i < split.size(); i++) // , 하나 넘겨야 하니까 i++
    {
        int numLen = getNumLen(idxTuple, split[i]);
        answer.push_back(stoi(split[i].substr(idxTuple, numLen)));
        idxTuple += numLen;
    }
    return answer;
}

하지만 또 테케를 똑바로 안 본 죄

3},
2,3}}
4,2,3},
2,3,4,1},

요따구로 들어올 수가 있다.

하지만 여기다가 set만 추가하면 될 것 같다.

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_set>

using namespace std;

vector<string>	ft_split(string s, char sep) // 구분자 하나짜리
{
	vector<string>	res;
	int	start_idx = 0;

	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] == sep)
		{
			if (i > start_idx)
				res.push_back(s.substr(start_idx, i - start_idx));
			start_idx = i + 1;
		}
	}
		if (start_idx < s.size())
			res.push_back(s.substr(start_idx, s.size() - start_idx));
	return (res);
}

bool    cmp(string a, string b)
{
    return (a.size() < b.size());
}

int getNumLen(int i, string s) // 현재 튜플안의 숫자의 길이 리턴
{
    int res = 0;
    while (s[i + res] != ',' && s[i + res] != '}')
        res++;
    return (res);
}

vector<int> solution(string s) {
    vector<int>         answer;
    vector<string>      split = ft_split(s, '{'); // "숫자, 숫자, 숫자}," 이런식으로 잘리게 된다.
    unordered_set<int>  set;
    
    sort(split.begin(), split.end(), cmp);
    for (int i = 0; i < split.size(); i++) // , 하나 넘겨야 하니까 i++
    {
        int idxTuple = 0;
        while (split[i][idxTuple] != ',' && split[i][idxTuple] != '}')
        {
            int numLen = getNumLen(idxTuple, split[i]);
            int curNum = stoi(split[i].substr(idxTuple, numLen));
            if (set.find(curNum) == set.end()) // 없는거 == 새로 생긴 인자면
            {
                set.insert(curNum);
                answer.push_back(curNum);
                break ;
            }
            idxTuple += numLen + 1;
        }
    }
    return answer;
}

성불 완료...

근데 이거 2점오르네.... 눈물이 난다...

반응형
profile

그럴듯한 개발 블로그

@donghyk2

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!