[프로그래머스]문자열 밀기

allnight5·2022년 12월 7일
0

프로그래머스 입문

목록 보기
48/53

문자열 "hello"에서 각 문자를 오른쪽으로 한 칸씩 밀고 마지막 문자는 맨 앞으로 이동시키면 "ohell"이 됩니다. 이것을 문자열을 민다고 정의한다면 문자열 A와 B가 매개변수로 주어질 때, A를 밀어서 B가 될 수 있다면 몇 번 밀어야 하는지 횟수를 return하고 밀어서 B가 될 수 없으면 -1을 return 하도록 solution 함수를 완성해보세요.

파이썬 첫번째

def solution(A, B): 
    for i in range(0,len(B)+1):
        result = A[len(B)-i:len(B)]+A[0:len(B)-i]
        if result == B:
            return i
        
    return -1

파이썬 두번째

def solution(A, B): 
    for i in range(0,len(B)+1):
        if A == B:
            return i
        A = A[-1]+A[:-1]
        
    return -1

자바 첫번째

class Solution {
    public int solution(String A, String B) { 
        
        for(int i=0; i<A.length()+1; i++){
            if(A.equals(B)){
                return i;
            }
            A = A.charAt(A.length()-1)+A.substring(0,A.length()-1);
        }
        return -1;
    }
}

자바 두번째

class Solution {
    public int solution(String A, String B) {
        int answer = 0;
        if(A.equals(B)) return 0;

        while(answer<A.length()){
            answer++;
            A = A.substring(A.length()-1) + A.substring(0,A.length()-1);
            if(B.equals(A)) break;

        }
        if(answer==A.length()) answer = -1;

        return answer;
    }
}
profile
공부기록하기

0개의 댓글