Title:Robot Return to Origin 657
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/robot-return-to-origin/
1. 上下对比,左右对比
时间复杂度:O(n),一次一层for循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 上线对比,左右对比
* @param moves
* @return
*/
public static boolean judgeCircle(String moves) {
int udCount = 0;
int lrCount = 0;
for (int i = 0; i < moves.length(); i++) {
if (moves.charAt(i) == 'U') {
udCount++;
}
if (moves.charAt(i) == 'D') {
udCount--;
}
if (moves.charAt(i) == 'L') {
lrCount++;
}
if (moves.charAt(i) == 'R') {
lrCount--;
}
}
if (udCount == 0 && lrCount == 0) {
return true;
}
return false;
}