https://school.programmers.co.kr/learn/courses/30/lessons/120921
문자열 "hello"에서 각 문자를 오른쪽으로 한 칸씩 밀고 마지막 문자는 맨 앞으로 이동시키면 "ohell"이 됩니다. 이것을 문자열을 민다고 정의한다면 문자열 A
와 B
가 매개변수로 주어질 때, A
를 밀어서 B
가 될 수 있다면 밀어야 하는 최소 횟수를 return하고 밀어서 B
가 될 수 없으면 -1을 return 하도록 solution 함수를 완성해보세요.
0 < A의 길이 = B의 길이 < 100
A, B는 알파벳 소문자로 이루어져 있습니다.
A | B | result |
---|---|---|
"hello" | "ohell" | 1 |
"apple" | "elppa" | -1 |
"atat" | "tata" | 1 |
"abc" | "abc" | 0 |
"hello"를 오른쪽으로 한 칸 밀면 "ohell"가 됩니다.
"apple"은 몇 번을 밀어도 "elppa"가 될 수 없습니다.
"atat"는 오른쪽으로 한 칸, 세 칸을 밀면 "tata"가 되므로 최소 횟수인 1을 반환합니다.
"abc"는 밀지 않아도 "abc"이므로 0을 반환합니다.
import java.util.ArrayList;
class Solution {
public int solution(String A, String B) {
int answer = 0;
ArrayList<String> temp=new ArrayList<String>();
boolean isRoop=true;
int len=A.length();
int count=0;
for(int j=0;j<A.length();j++){
temp.add(String.valueOf(A.charAt(j)));
}
while(isRoop){
String forcheck="";
for(int j=0;j<A.length();j++){
forcheck+=temp.get(j);
}
if(forcheck.equals(B)){
isRoop=false;
break;
}
else{
String in=temp.get(len-1);
temp.add(0,in);
answer++;
}
if(answer>len){
answer=-1;
isRoop=false;
break;
}
}
return answer;
}
}
B
와 같은지 비교하는 문에서 ArrayList랑 해야하는데 자꾸 A
랑 비교하니까 값이 제대로 나오지 않았다!
그리고 temp의 제일 앞에 temp의 제일 뒤에 있는 값을 넣어줘서 비교했다!