L657 机器人能否返回原点
GitHub 账户:LuvnJoae 欢迎关注! https://github.com/LuvnJoae
GitHub 代码链接:https://github.com/LuvnJoae/Java_leetcode
思路与结果
代码
思路1代码
package Day5_4_18.L657;
public class Solution {
public boolean judgeCircle(String moves) {
int countX = 0;
int countY = 0;
char[] chars = moves.toCharArray();
for (char c : chars) {
if ( c == 'U'){
countY++;
}else if ( c == 'D'){
countY--;
}else if ( c == 'R'){
countX++;
}else if ( c == 'L'){
countX--;
}else {
return false;
}
}
if ( countX == 0 && countY == 0){
return true;
}else {
return false;
}
}
}
思路2 代码
package Day5_4_18.L657;
public class Solution2 {
public boolean judgeCircle(String moves) {
int[] count = new int[26];
for (char c : moves.toCharArray()) {
count[c - 'A']++;
}
return count['L' - 'A'] == count['R' - 'A'] && count['U' - 'A'] == count['D' - 'A'];
}
}