문제 설명
문자열 code가 주어집니다.
code를 앞에서부터 읽으면서 만약 문자가 "1"이면 mode를 바꿉니다. mode에 따라 code를 읽어가면서 문자열 ret을 만들어냅니다.
mode는 0과 1이 있으며, idx를 0 부터 code의 길이 - 1 까지 1씩 키워나가면서 code[idx]의 값에 따라 다음과 같이 행동합니다.
- mode가 0일 때
- code[idx]가 "1"이 아니면 idx가 짝수일 때만 ret의 맨 뒤에 code[idx]를 추가합니다.
- code[idx]가 "1"이면 mode를 0에서 1로 바꿉니다.
- mode가 1일 때
- code[idx]가 "1"이 아니면 idx가 홀수일 때만 ret의 맨 뒤에 code[idx]를 추가합니다.
- code[idx]가 "1"이면 mode를 1에서 0으로 바꿉니다.
문자열 code를 통해 만들어진 문자열 ret를 return 하는 solution 함수를 완성해 주세요.
단, 시작할 때 mode는 0이며, return 하려는 ret가 만약 빈 문자열이라면 대신 "EMPTY"를 return 합니다.
제한사항
- 1 ≤ code의 길이 ≤ 100,000
- code는 알파벳 소문자 또는 "1"로 이루어진 문자열입니다.
입출력 예
code result
"abc1abc1abc" | "acbac" |
입출력 예 설명
입출력 예 #1
- code의 각 인덱스 i에 따라 다음과 같이 mode와 ret가 변합니다.
i code[i] mode ret
0 | "a" | 0 | "a" |
1 | "b" | 0 | "a" |
2 | "c" | 0 | "ac" |
3 | "1" | 1 | "ac" |
4 | "a" | 1 | "ac" |
5 | "b" | 1 | "acb" |
6 | "c" | 1 | "acb" |
7 | "1" | 0 | "acb" |
8 | "a" | 0 | "acba" |
9 | "b" | 0 | "acba" |
10 | "c" | 0 | "acbac" |
따라서 "acbac"를 return 합니다.
#include <string>
#include <vector>
using namespace std;
string solution(string code) {
string answer = "";
string ret = "";
bool mode = false;
for(int i=0; i<code.size(); i++){
if(code[i] == '1') mode = !mode;
else if(mode == false && i%2==0) ret += code[i];
else if(mode == true && i%2==1) ret += code[i];
}
if(ret.empty()) answer = "EMPTY";
else answer = ret;
return answer;
}
오 조금 시간이 걸린 코드였다 중간에 1이 문자열에 자꾸 들어가서 살짝 고생했지만
if문을 전체로 묶어서 했으면 될만한 문제였다.. 그렇게 어려운 문제는 아니였는데 ㅠㅜ 다음부터는 꼼꼼히 보자..
'프로그래머스(코딩테스트 연습)' 카테고리의 다른 글
프로그래머스/C++ 원소들의 곱과 합 (0) | 2023.09.26 |
---|---|
프로그래머스/C++ 등차수열의 특정한 항만 더하기 (0) | 2023.09.25 |
프로그래머스/C++ flag에 따라 다른 값 반환하기 (0) | 2023.09.24 |
프로그래머스/C++ 조건문자열 (0) | 2023.09.24 |
프로그래머스 홀짝에 따라 다른 값 변환하기 C++ (0) | 2023.09.23 |