C,C++

[C++] 프로그래머스 코딩테스트 입문_문자열 밀기

ab0utcom 2026. 2. 10. 16:41

최종코드:

#include <string>
#include <vector>

using namespace std;

// 오른쪽으로 n번 밀린 문자열 구하기
string pushString(string msg, int n) {
    if (msg.empty()) return msg;
    if (n==0) return msg;
    
    int L = msg.size();
    n %= L;     // n>L인 경우 방어
    
    string front = msg.substr(0, L-n);
    string back = msg.substr(L-n);
    return back + front;
}

int solution(string A, string B) {
    int answer = -1;
    
    for (int i=0; i<A.size(); i++) {
        // A의 첫문자가 발견되는 위치에서만 확인
        if (A.front() != B[i]) continue;
        
        // 발견했을 때 : 밀어야 하는 수 리턴
        if (pushString(A, i) == B) return i;
    }
    // 발견 못했을 때
    return -1;
}

for문을 돌면서 그때그때 밀어보고 확인하기보다는, 그러한 후보들 중에서만 작동하는 것으로 성능을 높였다.