-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJudgeRouteCircle.java
More file actions
64 lines (57 loc) · 1.64 KB
/
JudgeRouteCircle.java
File metadata and controls
64 lines (57 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package learn.ds.string;
/**
* @author Varma Penmetsa
*
* Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle,
* which means it moves back to the original place.
*
* The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right),
* L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
*
* Example 1:
* Input: "UD"
* Output: true
*
* Example 2:
* Input: "LL"
* Output: false
*
* https://leetcode.com/problems/judge-route-circle/description/
*/
public class JudgeRouteCircle {
/**
* Time Complexity : O(n)
* Space Complexity : O(1)
*/
public static boolean judgeCircle(String moves) {
if(moves == null || moves.length() == 0){
return true;
}
if(moves.length() % 2 != 0){
return false;
}
int lCount = 0;
int rCount = 0;
int uCount = 0;
int dCount = 0;
for(char c : moves.toCharArray()){
if(c == 'L'){
lCount = lCount + 1;
}else if(c == 'R'){
rCount = rCount + 1;
}else if(c == 'U'){
uCount = uCount + 1;
}else if(c == 'D'){
dCount = dCount + 1;
}
}
if(lCount == rCount && uCount == dCount){
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(judgeCircle("LL"));
System.out.println(judgeCircle("LR"));
}
}