본문 바로가기

프로그래머스/lv0

문자열 밀기

/* 문자열 밀기
 * 문자열 "hello"에서 각 문자를 오른쪽으로 한 칸씩 밀고 마지막 문자는 맨 앞으로 이동시키면 "ohell"이 됩니다.
 * 이것을 문자열을 민다고 정의한다면 문자열 A와 B가 매개변수로 주어질 때,
 * A를 밀어서 B가 될 수 있다면 몇 번 밀어야 하는지 횟수를 return하고
 * 밀어서 B가 될 수 없으면 -1을 return 하도록 solution 함수를 완성해보세요.
 *
 * A        B           result
 * "hello"  "ohell"     1
 * "apple"  "elppa"     -1
 */
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class programmer_0_5 {
    static String A1 = "hello"static String B1 = "lohel";
    static String A2 = "apple"static String B2 = "elppa";
    static String A3 = "abc"static String B3 = "abc";
 
    public int solution(String A, String B){
        int answer = 0;
/*      다른사람 풀이 (java 11에서만 사용 가능)
        String tempB = B.repeat(3); //반복시킴 hellohellohello
        return tempB.indexOf(A);    //A와 같은 인덱스 반환
*/
        
        String[] ar = A.split("");
        String last = "";
 
        while(answer < ar.length){
            if(A.equals(B)) break;
            for(int i = (ar.length - 1); i >= 0; i--){
                if(i == 0)  ar[i] = last;
                else{
                    if(i == ar.length-1)    last = ar[i];
                    ar[i] = ar[i-1];
                }    
            }
            A = String.join("", ar);
            answer++;
        }
        if(answer == ar.length) answer = -1;
        return answer;
    }
    public static void main(String args[]){
        programmer_0_5 t = new programmer_0_5();
 
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(A1, B1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(A2, B2));
        System.out.println("---------------------------------------");
        System.out.println("result3 = " + t.solution(A3, B3));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv0' 카테고리의 다른 글

연속된 수의 합  (0) 2022.12.06
종이 자르기  (0) 2022.12.06
잘라서 배열로 저장하기  (0) 2022.12.06
7의 개수  (0) 2022.12.06
문자열 정렬하기(2)  (0) 2022.12.06