LeetCode 第 X 题:Directions Reduction(方向简化)

1、前言

一个人被告知去一个地方怎么走:方向是”NORTH”, “SOUTH”, “WEST”, “EAST”,显然先NORTH再SOUTH等于没走,先WEST再EAST也是没走。这个路径简化后就是个“”;
现在给出一个路径,要求将其简化。注意,只简化相连的两个方向,如 ["NORTH", "EAST", "SOUTH"],NORTH 和 SOUTH 就不能简化,因为不相邻。

2、思路

这道题的思路用栈来做,跟有效括号是一个思想。括号是左括号遇到右括号就出栈,而这个也是此方向遇到另一个方向就出栈。

3、代码

public class Test4 {


    public String[] dirReduc(String[] arr) {
        if (arr == null || arr.length == 0) {
            return arr;
        }

        Stack stack = new Stack<>();

        for (String direct : arr) {
            if (!stack.isEmpty() && (
                    (direct == "NORTH" && stack.peek() == "SOUTH")
                            || (direct == "SOUTH" && stack.peek() == "NORTH")
                            || (direct == "EAST" && stack.peek() == "WEST")
                            || (direct == "WEST" && stack.peek() == "EAST"))) {
                stack.pop();
            }else {
                stack.push(direct);
            }
        }

        return stack.toArray(new String[]{});
    }

    public static void main(String[] args) {
        String[] res = new Test4().dirReduc(new String[]{"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"});
        for (String re : res) {
            System.out.print(re + ", ");
        }
    }
}

你可能感兴趣的:(LeetCode 第 X 题:Directions Reduction(方向简化))