게임 캐릭터를 4가지 명령어를 통해 움직이려 합니다. 명령어는 다음과 같습니다.
U: 위쪽으로 한 칸 가기
D: 아래쪽으로 한 칸 가기
R: 오른쪽으로 한 칸 가기
L: 왼쪽으로 한 칸 가기
캐릭터는 좌표평면의 (0, 0) 위치에서 시작합니다. 좌표평면의 경계는 왼쪽 위(-5, 5), 왼쪽 아래(-5, -5), 오른쪽 위(5, 5), 오른쪽 아래(5, -5)로 이루어져 있습니다.
명령어가 매개변수 dirs로 주어질 때, 게임 캐릭터가 처음 걸어본 길의 길이를 구하여 return 하는 solution 함수를 완성해 주세요.
dirs answer
"ULURRDLLU" 7
"LULLLLLLU" 7
import java.util.*;
class Solution {
public int solution(String dirs) {
int answer = 0;
int x = 0;
int y = 0;
int beforeX = 0;
int beforeY = 0;
Set<String> result = new HashSet<>();
for(int i = 0; i < dirs.length(); i++){
beforeX = x;
beforeY = y;
String position = "";
if(dirs.charAt(i) == 'U' && x < 5){
x++;
}else if(dirs.charAt(i) == 'D' && x > -5){
x--;
}else if(dirs.charAt(i) == 'L' && y > -5){
y--;
}else if(dirs.charAt(i) == 'R' && y < 5){
y++;
}else{
continue;
}
position += x;
position += y;
position += beforeX;
position += beforeY;
result.add(position);
}
answer = result.size();
return answer;
}
}
import java.util.*;
class Solution {
public int solution(String dirs) {
int answer = 0;
int x = 0;
int y = 0;
int beforeX = 0;
int beforeY = 0;
Set<String> result = new HashSet<>();
for(int i = 0; i < dirs.length(); i++){
beforeX = x;
beforeY = y;
String position = "";
if(dirs.charAt(i) == 'U' && x < 5){
x++;
position += x;
position += y;
position += beforeX;
position += beforeY;
}else if(dirs.charAt(i) == 'D' && x > -5){
x--;
position += beforeX;
position += beforeY;
position += x;
position += y;
}else if(dirs.charAt(i) == 'L' && y > -5){
y--;
position += beforeX;
position += beforeY;
position += x;
position += y;
}else if(dirs.charAt(i) == 'R' && y < 5){
y++;
position += x;
position += y;
position += beforeX;
position += beforeY;
}else{
continue;
}
result.add(position);
}
answer = result.size();
return answer;
}
}
https://school.programmers.co.kr/learn/courses/30/lessons/49994