Leetcode 657 机器人能否回到原点
JAVA 遍历:
public final boolean judgeCircle(String moves) { int x = 0, y = 0; for (int i = 0; i < moves.length(); i++) { char c = moves.charAt(i); switch (c) { case 'L': x--; break; case 'R': x++; break; case 'U': y++; break; case 'D': y--; break; } } return x == 0 && y == 0; }
JAVA 栈辅助:
public final boolean judgeCircle(String moves) { Stack<Character> uStack = new Stack<Character>(); Stack<Character> dStack = new Stack<Character>(); Stack<Character> lStack = new Stack<Character>(); Stack<Character> rStack = new Stack<Character>(); for (int i = 0; i < moves.length(); i++) { Stack<Character> t = null, s = null; switch (moves.charAt(i)) { case 'L': t = rStack; s = lStack; break; case 'R': t = lStack; s = rStack; break; case 'U': t = dStack; s = uStack; break; case 'D': t = uStack; s = dStack; break; } popOrPush(moves.charAt(i), t, s); } return uStack.empty() && dStack.empty() && lStack.empty() && rStack.empty(); } private final void popOrPush(char c, Stack<Character> t, Stack<Character> s) { if (t.empty()) s.push(c); else t.pop(); }
JS 栈辅助:
/** * @param {string} moves * @return {boolean} */ var judgeCircle = function (moves) { var u = [], d = [], l = [], r = []; for (let i = 0; i < moves.length; i++) { let c = moves.charAt(i); popOrPush(c, u, d, l, r); } return u.length == 0 && d.length == 0 && l.length == 0 && r.length == 0; } var popOrPush = (c, u, d, l, r) => { let stack0, stack1; switch (c) { case 'U': stack0 = d; stack1 = u; break; case 'D': stack0 = u; stack1 = d; break; case 'L': stack0 = r; stack1 = l; break; case 'R': stack0 = l; stack1 = r; } if (stack0.length == 0) stack1.push(c); else stack0.pop(); }
当你看清人们的真相,于是你知道了,你可以忍受孤独