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

2023. 1. 31. 20:04알고리즘

728x90

문제 설명

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

제한사항

  • 0 < A의 길이 = B의 길이 < 100
  • A, B는 알파벳 소문자로 이루어져 있습니다.

입출력 예

입출력 예 설명

입출력 예 #1

  • "hello"를 오른쪽으로 한 칸 밀면 "ohell"가 됩니다.

입출력 예 #2

  • "apple"은 몇 번을 밀어도 "elppa"가 될 수 없습니다.

입출력 예 #3

  • "atat"는 오른쪽으로 한 칸, 세 칸을 밀면 "tata"가 되므로 최소 횟수인 1을 반환합니다.

입출력 예 #4

  • "abc"는 밀지 않아도 "abc"이므로 0을 반환합니다.

코드 설명

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Solution {
//	public int solution(String A, String B) {		
//        int answer = 0;
//        String result = A;							
//        
//        for (int i = 0; i < A.length(); i++) {		
//        	if (result.equals(B)) {					
//        		return answer;
//        	}
//        	String a = result.substring(result.length() - 1);		
//            result = a + result.substring(0, result.length() - 1);	
//            answer++;												
//        }															
//        
//        return -1;
//    }
	public int solution(String A, String B) {
        return (B + B).indexOf(A);				
    }
//	public static void main(String[] args) {
//		Solution T = new Solution();
//		Scanner sc = new Scanner(System.in);
//		String A = sc.next();
//		String B = sc.next();
//		System.out.println(T.solution(A, B));
//		sc.close();
//	}
	public static void main(String[] args) throws IOException {
		Solution T = new Solution();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String A = br.readLine();
		String B = br.readLine();
		System.out.println(T.solution(A, B));
		br.close();
	}
}

ex) A = "hello", B = "ohell" 일 때

 

String result = A;

result = "hello"

 

if (result.equals(B)) { 

         return answer;

    }

만약 result = "ohell" 이면 answer 출력

 

String a = result.substring(result.length() - 1)

a = "hello"에서 4번째 자리 "o" 를 저장시켜주고

 

result = a + result.substring(0, result.length() - 1)

result에 "o" + "hell"("hello"에서 0 ~ 3번째 자리까지 가져옴)

 

answer++;

한번씩 바꿀때 마다 answer 1증가

 

return -1;

A.length 만큼 바꿨는데 B랑 같지 않으면 -1 출력

 

한 줄로도 구할 수 있는 방식이 있다.

return (B + B).indexOf(A);

ex) A = "hello" B = "ohell" 일 때 "ohellohell"에서 A문자열 찾으면 1번째 자리 에서 hello 가 찾아지니 1이 return됨.

728x90