leetcode 20 + leetcode 146
阿新 • • 發佈:2022-04-21
給定一個只包括 '(',')','{','}','[',']' 的字串 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; }