프로그래머스 레벨0_ 문자열 섞기
2025. 2. 23. 14:27ㆍ개발자 능력치 물약/C++
작성코드
#include <string>
#include <vector>
using namespace std;
string solution(string str1, string str2) {
string answer = "";
str1.append(str1);
//str2값을 answer짝수번에 복사
for(int i = 0; i < str2.size(); i++){
str1[2 * i + 1] = str2[i];
}
answer = str1;
return answer;
}
실행결과
str1이 순서가 있는 문자열일 경우 실행 결과가 일치 하지 않았다.
원인
str1.append(str1); // str1이 "abcde"에서 "abcdeabcde"가 됨
for (int i = 0; i < str2.size(); i++){
str1[2 * i + 1] = str2[i];
}
이 부분을 실행하면 i=0: str1[1]는 'b' → 변경 전에도 'b'라서 그대로 i=1: str1[3]는 원래 'd' → 'b'로 변경
i=2: str1[5]는 원래 'a' → 'b'로 변경 i=3: str1[7]는 원래 'c' → 'b'로 변경
i=4: str1[9]는 원래 'e' → 'b'로 변경
최종 결과는 "abcbebbbdb"가 되어 원하는 “번갈아 나오는” (즉, str1[0], str2[0], str1[1], str2[1], …) 결과와는 차이가 발생합니다.
따라서 번갈아가면서 str1 과 str2의 값을 문자열에 넣어주면 됩니다.
수정코드
#include <string>
using namespace std;
string solution(string str1, string str2) {
int n = str1.size();
string answer(2 * n, ' '); // 결과 문자열의 길이는 2*n
for (int i = 0; i < n; i++) {
answer[2 * i] = str1[i];
answer[2 * i + 1] = str2[i];
}
return answer;
}
'개발자 능력치 물약 > C++' 카테고리의 다른 글
0315 형변환 , L/Rvalue (0) | 2025.03.15 |
---|---|
인라인 함수와 매크로의 차이 (0) | 2025.03.10 |
프로그래머스 레벨0: 두 수의 연산값 비교하기 (0) | 2025.02.23 |
프로그래머스 레벨 0: 더 크게 합치기 (0) | 2025.02.23 |
프로그래머스_레벨0_문자열겹쳐쓰기 (0) | 2025.02.23 |