[프로그래머스/C++]Lv.1 - 이상한 문자 만들기

YH J·2023년 6월 7일
0

프로그래머스

목록 보기
120/168

문제 링크

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

내 풀이

index 기반 for문으로 순회하면서 알파벳을 변환하는데 외부 변수 count를 기반으로 짝수번째인지 홀수번째인지 체크한다. 탐색하다가 공백을 만나면 count를 초기화한다. ( 단어(공백을 기준)별로 짝/홀수 인덱스를 판단해야합니다 의 조건때문)

내 코드

#include <string>
#include <vector>

using namespace std;

string solution(string s) {
    int count = 0;
    for(int i = 0; i < s.length(); i++)
    {
        if(s[i] == ' ')
        {
            count = 0;
            continue;
        }
        if(count%2)
            s[i] = tolower(s[i]);
        else
            s[i] = toupper(s[i]);
        count++;
    }   
    return s;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

string solution(string s) {
    string answer = "";
    int nIndex = 1;
    for (int i = 0; i < s.size(); i++, nIndex++)
    {
        if (s[i] == ' ')
        {
            nIndex = 0;
            answer += " ";
        }
        else
            nIndex & 1 ? answer += toupper(s[i]) : answer += tolower(s[i]);
    }

    return answer;
}

다른 사람의 풀이 해석

s를 바꾸지 않고 answer에 재조합하였다.

profile
게임 개발자 지망생

0개의 댓글