【面試演算法題】一維消除遊戲

alicelmx發表於2019-08-12

題目說明

三個或者三個以上顏色相同就刪除
比如:紅紅黃黃綠綠綠綠黃藍 消除完了之後是 紅紅藍

實現程式碼

package leetcoode;

import java.util.LinkedList;
public class XiaoXiaoLe {
    public static void main(String[] args) {
//        String[] arr = {"red","red","yellow","yellow","green","green","green","green","yellow","blue"};
        String[] arr = {"red","red","red"};
        LinkedList<String> stack = new LinkedList<String>();
        for(int i = 0; i < arr.length; i ++) {
            String cur = arr[i];
            String last = i < arr.length - 1 ? arr[i + 1] : "";
            if(stack.isEmpty() || !stack.peekLast().equals(cur) || cur.equals(last)) {
                stack.add(cur);
            } else {
                String t1 = !stack.isEmpty() ? stack.peekLast() : "";
                String t2 = stack.size() > 1 ? stack.get(stack.size() - 2) : "";
                if(cur.equals(t1) && cur.equals(t2)) {
                    while(!stack.isEmpty() && stack.peekLast().equals(cur)) {
                        stack.pollLast();
                    }
                } else {
                    stack.add(cur);
                }
            }
        }
        if(stack.size()==0)
        	System.out.println("所有顏色均被消除!");
        else {
        	for(String color : stack)
                System.out.println(color);
        }
    }
}

相關文章