【一次過】Lintcode 1104. Judge Route Circle
阿新 • • 發佈:2018-12-10
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 finally.
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
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
解題思路:
大致的題意是:不管怎麼動,判斷最終是否回到了原點。由於只有四個方向,兩兩為一組,即Up,Down一組,Left,Right一組,同一組方向上有影響,不同組方向上不影響。
所以使用兩個棧來存放UD和LR,以UD這組為例,當U壓入棧時,棧為空或者棧頂元素為U,則可以將U壓入,棧頂為D,則可以抵消,將棧頂彈出。遍歷到最後,如果兩個棧仍然為空,則表明兩組方向上兩兩抵消,最終肯定會回到原點。
所以這題看著很多,其實與括號匹配的題目非常類似。
public class Solution { /** * @param moves: a sequence of its moves * @return: if this robot makes a circle */ public boolean judgeCircle(String moves) { // Write your code here if(moves.length()==0) return true; Stack<Character> stk1 = new Stack<>(); //用於儲存UD Stack<Character> stk2 = new Stack<>(); //用於儲存LR for(int i=0 ; i<moves.length() ; i++){ if(moves.charAt(i) == 'U' || moves.charAt(i) == 'D'){ //UD情況 if(stk1.empty() || stk1.peek()==moves.charAt(i)){ stk1.push(moves.charAt(i)); }else{ //stk1棧頂為相反的情況 stk1.pop(); } }else{ //LR情況 if(stk2.empty() || stk2.peek()==moves.charAt(i)){ stk2.push(moves.charAt(i)); }else{ //stk2棧頂為相反的情況 stk2.pop(); } } } if(stk1.empty() && stk2.empty()) return true; else return false; } }