算法(四十七)

48 篇文章 0 订阅

1、**判断一个运算表达式的左右括号是否全部合法**
public class test010 {
    private HashMap<Character, Character> mappings;
    public test010() {
        this.mappings = new HashMap<Character, Character>();
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');
    }
    public boolean isValid(String s) {

        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (this.mappings.containsKey(c)) {

                char topElement = stack.empty() ? '#' : stack.pop();

                if (topElement != this.mappings.get(c)) {
                    return false;
                }
            } else {
                if(c=='('||c=='['||c=='{'){
                    stack.push(c);
                }
            }
        }
        return stack.isEmpty();
    }
}

2、手撕LRUMap。
解题思路
LinkedList储存key值,实现最近最少使用。
get:
如果存在该key,则先把LinkedList中原来的key值删除,再把key添加到LinkedList末尾,越最近使用的key越靠近LinkedList末尾。
put:

如果存在该key,也要像get一样,先把LinkedList中原来的key值删除,再把key添加到LinkedList末尾,直接调用HashMap的put方法,新的value值就会覆盖旧的value值。
如果put之前元素个数已经达到了容量,则把LinkedList中第一个元素删除,越是最近最少使用的key越靠近LinkedList头部。然后调用HashMap的put方法。
不存在该key,也没有到达容量,直接调用HashMap的put方法。
代码
class LRUCache {
    private int capacity;
    private HashMap<Integer,Integer> map;
    private LinkedList<Integer> list;
    public LRUCache(int capacity) {
        this.capacity=capacity;
        map=new HashMap<>();
        list=new LinkedList<>();
    }
    
    public int get(int key) {
        if(map.containsKey(key)){
            list.remove((Integer)key);
            list.addLast(key);
            return map.get(key);
        }
        return -1;
    }
    
    public void put(int key, int value) {
        if(map.containsKey(key)){
            list.remove((Integer)key);
            list.addLast(key);
            map.put(key,value);
            return;
        }
        if(list.size()==capacity){
            map.remove(list.removeFirst());
            map.put(key,value);
            list.addLast(key);
        }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值