leetcode 20 + leetcode 146

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

示例 1:

输入:s = "()"
输出:true
示例 2:

输入:s = "()[]{}"
输出:true
示例 3:

输入:s = "(]"
输出:false
示例 4:

输入:s = "([)]"
输出:false
示例 5:

输入:s = "{[]}"
输出:true

class Solution {
public:
    bool isValid(string s) {
        stack<int> st;
        for(int i=0;i<s.size();i++){
            if(s[i]=='(') st.push(')');
            else if(s[i]=='{') st.push('}');
            else if(s[i]=='[') st.push(']');
            else if(st.empty()||st.top()!=s[i]) return false;
            else st.pop();
        }
        return st.empty();
    }
};

请你设计并实现一个满足  LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。

#include <bits/stdc++.h>
using namespace std;
class LRUCache {
public:
    LRUCache(int capacity) : _capacity(capacity) {}
    int get(int key) {
        auto it = mp.find(key);
        if (it != mp.end()) {
            _lru.splice(_lru.begin(), _lru, it->second);
            return it->second->second;
        }
        return -1;
    }
    void put(int key, int value) {
        auto it = mp.find(key);
        if (it != mp.end()) {
            _lru.splice(_lru.begin(), _lru, it->second);
            it->second->second = value;
            return;
        }
        _lru.emplace_front(key, value);
        mp[key] = _lru.begin();
        if (mp.size() > _capacity) {
            mp.erase(_lru.back().first);
            _lru.pop_back();
        }
    }

private:
    unordered_map<int, list<pair<int, int>>::iterator> mp;
    std::list<std::pair<int, int>> _lru;
    int _capacity;
};
void test0() {
    LRUCache lr(2);
    lr.put(1, 1);
    cout << "get(1)= " << lr.get(1) << endl;
    lr.put(3, 3);
    cout << "get(2) = " << lr.get(2) << endl;

    lr.put(4, 4);
    cout << "get(1) = " << lr.get(1) << endl;

    cout << "get(3) = " << lr.get(3) << endl;
    cout << "get(4) = " << lr.get(4) << endl;
}
int main() {
    test0();
    return 0;
}
posted @ 2022-04-21 22:05  Fancele  阅读(46)  评论(0)    收藏  举报