문제

문제 해석
- 0번 인덱스의 음식은 물
- 1번부터 food를 앞(index 증가), 뒤(index 감소)로 index 값을 넣어주면 된다.
- 문자열로 반환할 것이므로 index는 to_string()을 사용해 문자로 변환
- food는 앞 뒤로 넣으므로 최소 2개가 존재해야 넣을 수 있다. 나눗셈 연산 사용
- food는 앞 뒤로 2개를 넣었으므로 2개를 빼준다.
- 다 넣었으면 문자열 중간에 0번 인덱스(물)를 넣어준다.
코드
#include <string>
#include <vector>
using namespace std;
string solution(vector<int> food) {
string answer = "";
int insertCount = 0;
for(int IDX = 1; IDX < food.size(); ++IDX)
{
// 해당 인덱스의 food가 2개 이상이면 앞 뒤로 넣을 수 있다.
while(food[IDX] / 2 > 0)
{
answer.insert(insertCount, to_string(IDX));
answer.insert(answer.length() - insertCount, to_string(IDX));
++insertCount;
food[IDX] -= 2;
}
}
answer.insert(answer.length() / 2, to_string(0));
return answer;
}
다른 사람의 풀이
- 이중 반복문을 사용, 다른 점은 마지막 부터 Index를 시작시켜 문자열을 안쪽부터 바깥쪽으로 붙여나가며 풀이
answer = to_string(i) + answer + to_string(i);
- O(n), string::insert()의 오버라이드 함수인 string& insert(size_t pos, size_t n, char c)를 이용하여 앞 뒤로 문자열을 붙이는 풀이.
'코딩 테스트 > 프로그래머스' 카테고리의 다른 글
| 명예의 전당 (1) (2) | 2025.01.16 |
|---|---|
| 콜라 문제 (2) | 2025.01.16 |
| 두 개 뽑아서 더하기 (0) | 2025.01.14 |
| 가장 가까운 같은 글자 (1) | 2025.01.14 |
| 숫자 문자열과 영단어 (2) | 2025.01.13 |