코드 흐름
- Move 클래스를 통해서 이동을 했을 때 시작점위치와 끝점위치를 저장하는 객체 선언
- Move는 객체이기에 equals 연산에서 hashcode만 달라도 인스턴스가 같다한들 다른 것으로 판단되기에 equals와 hashcode 를 override
- HashSet으로 중복제거 메커니즘을 사용
- 입력으로 받은 dirs에서 charAt으로 하나씩 명령어 가져오기
- 명령어에 맞게끔 x와 xx, y와 yy를 수정
- moves set에 밖으로 나간게 아니라면 시작점에서 끝점, 끝점에서 시작점으로 오는 Move를 둘다 저장
- return 시 왕복까지 모두 해놓았기에 HashSet의 크기/2 를 리턴
import java.util.*;
class Move{
int startx,starty;
int endx,endy;
public Move(int a, int b, int c, int d){
startx = a;
starty = b;
endx = c;
endy = d;
}
@Override
public boolean equals(Object o){
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
Move move = (Move) o;
return startx == move.startx && starty == move.starty
&& endx == move.endx && endy == move.endy;
}
@Override
public int hashCode(){
return Objects.hash(startx,starty,endx,endy);
}
}
class Solution {
public int solution(String dirs) {
int x=0, y=0, xx, yy;
HashSet<Move> moves = new HashSet<>();
for(int i = 0 ; i < dirs.length() ; i++){
char dir = dirs.charAt(i);
if(dir == 'U'){ yy = y+1; xx = x;}
else if(dir == 'D'){ yy = y-1; xx = x;}
else if(dir == 'R'){ xx = x+1; yy = y;}
else{ xx = x-1; yy = y;}
if (xx >= -5 && xx <= 5 && yy >= -5 && yy <= 5) {
moves.add(new Move(x,y,xx,yy));
moves.add(new Move(xx,yy,x,y));
x = xx;
y = yy;
}
}
return moves.size()/2;
}
}
'Algorithm & Data Structures > Programers' 카테고리의 다른 글
Lv 2. 쿼드압축 후 갯수 세기 (0) | 2024.07.29 |
---|---|
Lv 2. 가장 큰 수 (0) | 2024.07.26 |
Lv 2. 2개 이하로 다른 비트 (0) | 2024.07.23 |
Lv 2. n제곱배열자르기 (4) | 2024.07.22 |
Lv 2. 프렌즈4블록 (0) | 2024.07.21 |