Jam's story
[프로그래머스]문자열 밀기 java 본문
String문자열을 String 배열로 쪼개기
String[] str=A.split(" ");
문자열.split(" ");
String문자열을 char 배열로 쪼개기
문자열.toCharArray();
내풀이
package lv0;
public class 문자열밀기 {
public static int solution(String A, String B) {
int answer = 0;
int findIdx=0;
char[] arrA=A.toCharArray();
char[] arrB=B.toCharArray();
String[] arA=A.split(" ");
String[] arB=B.split(" ");
for (char c : arrA) {
if(c==arrB[0]) {
findIdx=A.indexOf(c);
answer=A.length()-findIdx;
String subs=" ";
subs+=A.substring(findIdx);
subs+=A.substring(0, findIdx);
System.out.println(B+", "+subs);
if(!subs.equals(B)) {answer=-1;
System.out.println(subs.equals(B));}
}
}//for
return answer;
}
public static void main(String[] args) {
String A="hello";
String B="ohell";
//hello lohel 2
solution(A,B);
String C="apple";
String D="elppa";
solution(C,D);
String E="hello";
String F="elloh";
solution(E,F);
}
}
if(!subs.equals(B)) {answer=-1;
System.out.println(subs.equals(B));}
}
이부분이 제대로 안되는 것이 문제
정답풀이
package lv0;
import java.util.Iterator;
public class Main{
public static int solution(String A, String B) {
int result=-1;
if(A.equals(B)) result=0;
String addstr=" ";
for (int i = 0; i < A.length(); i++) {
//맨끝문자를 저장할 변수
//substring은 매개변수가 하나면 beginIndex~ 끝 을 나타난다.
//인덱스가 맨 마지막 인덱스를 가르키니, 맨 마지막 글자만 추출한다.
String end=A.substring(A.length()-1);
//substring 할 변수
String temp=end+A.substring(0,A.length()-1);
//이 두개를 합칠 변수
A=temp;
System.out.println(i+", "+A);
if(A.equals(B)) {
result=i+1;
System.out.println("result: "+result);
}
}//for
return 0;
}
public static void main(String[] args) {
String A="hello";
String B="ohell";
//hello lohel 2
System.out.println(solution(A,B));
String C="apple";
String D="elppa";
System.out.println(solution(C,D));
String E="hello";
String F="elloh";
System.out.println(solution(E,F));
}
}
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 문자열 정렬하기(2) JAVA (0) | 2022.12.21 |
---|---|
[프로그래머스] 잘라서 배열로 저장하기 java (0) | 2022.12.13 |
[프로그래머스] 종이자르기 java (0) | 2022.12.12 |
[프로그래머스] 다음에 올 숫자 - java (0) | 2022.12.09 |
[프로그래머스] n의 배수 고르기 (0) | 2022.11.20 |
Comments