[Algorithms] Programmers / 문자열 밀기

Onam Kwon·2022년 12월 3일
0

Algorithms

목록 보기
21/24
post-thumbnail

문자열 밀기

링크

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

풀이

  • 문자열 A를 오른쪽 방향으로 한번씩 회전하면서 B가 될때까지 반복 후 회전 횟수를 반환하는 문제이며 A와 B가 다를경우 마지막에 -1을 반환하는 문제.
  • foo1 방식으로 푼 다음 다른사람의 풀이를 구경하다가 눈에띄는 풀이가 있어서 기록한다.
  • 함수 foo1foo2는 결과적으로 정확히 같다.

코드

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string A = "hello";
string B = "ohell";

/**
 * Problem: Rotating string to the right side means shift every elements of the string to the right side. 
 * The right most element goes to the left most element.
 * Find the rotated number that A to be B.
 * 
 * Function foo1 and function foo2 are doing the same thing.
 */

int foo1(string A, string B) {
    int answer = 0;
    for(int i=0;i<A.size();i++) {
        if(A==B) return answer;
        rotate(A.rbegin(), A.rbegin()+1, A.rend());
        answer++;
    }
    return -1;
}

int foo2(string A, string B) {
    B += B;
    return B.find(A);
}

int main() {

    cout<<"foo1: "<<foo1(A, B)<<endl;
    cout<<"foo2: "<<foo2(A, B)<<endl;

    return 0;
}

🔽Output🔽

foo1: 1
foo2: 1

Github

profile
권오남 / Onam Kwon

0개의 댓글