https://school.programmers.co.kr/learn/courses/30/lessons/42860
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
- 처음 작성한 잘못된 풀이
class Solution {
public int solution(String name) {
int answer = 0;
char[] cName = name.toCharArray();
char[] aName = new char[cName.length];
int cursor = 0;
int a = aName.length;
for(int i = 0; i < a; i++){
aName[i] = 'A';
}
while(true){
if(aName[cursor] == cName[cursor]){
// A가 없는 쪽으로 이동 둘다 있으면 그냥 앞으로 이동
if(cursor == 0 || cursor == a-1){
if(cursor == 0){
if(aName[cursor+1] == cName[cursor+1] && aName[a-1] != cName[a-1]){
cursor = a-1;
answer++;
}else if(aName[cursor+1] != cName[cursor+1] && aName[a-1] == cName[a-1]){
cursor++;
answer++;
}else{
cursor++;
answer++;
}
}else{
if(aName[0] == cName[0] && aName[cursor-1] != cName[cursor-1]){
cursor--;
answer++;
}else if(aName[0] != cName[0] && aName[cursor-1] == cName[cursor-1]){
cursor = 0;
answer++;
}else{
cursor = 0;
answer++;
}
}
}else{
if(aName[cursor+1] == cName[cursor+1] && aName[cursor-1] != cName[cursor-1]){
cursor--;
answer++;
}else if(aName[cursor+1] != cName[cursor+1] && aName[cursor-1] == cName[cursor-1]){
cursor++;
answer++;
}else{
cursor++;
answer++;
}
}
}else{
if(cName[cursor] - aName[cursor] <= 12){
answer += (cName[cursor]-aName[cursor]);
}else{
answer += (26-(cName[cursor]-aName[cursor]));
}
aName[cursor] = cName[cursor];
if(String.valueOf(aName).equals(name)){
break;
}else{
//answer++;
continue;
}
}
}
return answer;
}
}
/*
1. 첫번째 위치에서 해당 알파벳 완성
2. 양쪽을 비교해서 A가 아닌 위치가 더 가까운 곳으로 옮겨감
3. 옮겨간 뒤 그 자리에 맞는 알파벳으로 갈아끼우고 다시 옮기기 반복
*/
- 정답 풀이
class Solution {
public int solution(String name) {
int answer = 0;
int length = name.length();
int index; // 다음 값들을 확인할 때 사용
int move = length - 1; // 좌우 움직임 수를 체크
for(int i = 0; i < name.length(); i++){
answer += Math.min(name.charAt(i) - 'A', 'Z' - name.charAt(i) + 1);
index = i + 1;
// 연속되는 A 갯수 확인
while(index < length && name.charAt(index) == 'A'){
index++;
}
// 순서대로 가는 것과, 뒤로 돌아가는 것 중 이동수가 적은 것을 선택
move = Math.min(move, i * 2 + length - index);
// BBBBAAAAAAAB 와 같이, 처음부터 뒷부분을 먼저 입력하는 것이 더 빠른 경우까지 고려하려면 아래의 코드가 필요
move = Math.min(move, (length - index) * 2 + i);
}
return answer + move;
}
}'코딩테스트 > 코딩테스트 문제풀이' 카테고리의 다른 글
| [Java] 프로그래머스 <K번째수> (0) | 2025.02.05 |
|---|---|
| [Java] 프로그래머스 <폰켓몬> (0) | 2025.02.05 |
| [Java] 프로그래머스 <같은 숫자는 싫어> (0) | 2025.02.04 |
| [Java] 백준 2018번 <수들의 합 5> (0) | 2024.03.27 |
| [Java] 백준 1260번 <DFS와 BFS> (0) | 2023.07.27 |