Directions Reduction

问题

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

例子

assertEquals("\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"",
        new String[]{"WEST"},
        DirReduction.dirReduc(new String[]{"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"}));

    assertEquals("\"NORTH\", \"WEST\", \"SOUTH\", \"EAST\"",
        new String[]{"NORTH", "WEST", "SOUTH", "EAST"},
        DirReduction.dirReduc(new String[]{"NORTH", "WEST", "SOUTH", "EAST"}));

我的代码


import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;


public class DirReduction {
    public static HashMap<String, String> map = new HashMap<String, String>();
    public static String[] dirReduc(String[] arr) {
        map.put("NORTH","SOUTH");
        map.put("WEST","EAST");
        map.put("SOUTH","NORTH");
        map.put("EAST","WEST");

        int position = 0;
        List<String> list = new LinkedList<>();
        for (String str : arr) {
            if (position == 0 || !iSReverse(list.get(position-1), str)) {
                list.add(str);
                position++;
                continue;
            } else {
                list.remove(position-1);
                position--;
            }
        }
        return list.toArray(new String[list.size()]);
    }
    public static boolean iSReverse(String oldStr, String newStr) {
        return oldStr.equals(map.get(newStr))? true : false;
    }

    public static void main(String[] args) {
        String[] result = DirReduction.dirReduc(new String[]{"NORTH", "WEST", "SOUTH", "EAST"});
        System.out.println(result);
    }
}

高手的代码

import java.util.Stack;

public class DirReduction {
    public static String[] dirReduc(String[] arr) {
        final Stack<String> stack = new Stack<>();

        for (final String direction : arr) {
            final String lastElement = stack.size() > 0 ? stack.lastElement() : null;

            switch(direction) {
                case "NORTH": if ("SOUTH".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
                case "SOUTH": if ("NORTH".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
                case "EAST":  if ("WEST".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
                case "WEST":  if ("EAST".equals(lastElement)) { stack.pop(); } else { stack.push(direction); } break;
            }
        }
        return stack.stream().toArray(String[]::new);
    }
}

分析

这道题本质上是一道出栈和入栈的实现问题。高手代码的一个值得学习的地方是用到的Stack这个实现栈功能的类,比我的代码高明,不需要维护一个位置指针。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值