【面试算法题】一维消除游戏

题目说明

三个或者三个以上颜色相同就删除
比如:红红黄黄绿绿绿绿黄蓝 消除完了之后是 红红蓝

实现代码

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);
        }
    }
}

你可能感兴趣的:(求职,面试中手撕过的那些题目)