코린이의 소소한 공부노트

[LeetCode/Easy] 657. Robot Return to Origin 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 657. Robot Return to Origin

무지맘 2022. 12. 4. 23:57

1. Input

1) 문자열 moves

2) moves에는 상, , , 4방향으로 각 1칸씩 움직이라는 명령어인 'U', 'D', 'L', 'R'이 담겨져있다.

 

2. Output

1) (0, 0)에 있는 로봇이 moves를 따라 움직였을 때 다시 (0, 0)으로 돌아왔다면 true, 아니라면 false를 반환

 

3. Constraint

1) 1 <= moves.length <= 2 * 104

2) moves에는 'U', 'D', 'L', 'R' 외의 다른 문자는 없다.

 

4. Example

Input: moves=“LL” -> Output: false

설명: 왼쪽으로 2번 움직이면 (-2, 0)이 되므로 원점으로 돌아오지 않아 false를 반환한다.

 

5. Code

1) 첫 코드(2022/06/16)

int[] counts = new int[2];
for(int i=0 ; i<moves.length() ; i++){
    if(moves.charAt(i) == 'U') counts[0]++;
    else if(moves.charAt(i) == 'D') counts[0]--;
    else if(moves.charAt(i) == 'L') counts[1]++;
    else counts[1]--;
}

return counts[0]==0 && counts[1]==0;