Java代码
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
// 定义缓存结构体(用到了LinkedHashMap数据结构)
class LRUCache {
private Map<Integer, Integer> map;
private int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
map = new LinkedHashMap<>(capacity);
}
public int get(int key) {
Integer value = map.get(key);
// 如果已经有此key
if(value != null){
if(map.size() > 1){
// 缓存中值的个数多于一个
map.remove(key); // 删除原先的key
map.put(key, value); // 将此key添加到最后
}
} else {
// 如果没有此key
return -1;
}
return value;
}
public void put(int key, int value) {
// 如果已有此key
if(map.containsKey(key)){
map.remove(key); // 删除原先的key
} else if(map.size() >= capacity){
// 如果此key是新值,且加入此key后,超过了缓存的最大值
Integer firstKey = map.keySet().iterator().next();
map.remove(firstKey);
}
map.put(key, value);
}
}
// 输入和输出
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.nextLine();
String s2 = scanner.nextLine();
// String s1 = "[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]";
// String s2 = "[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]";
String[] sc1 = s1.substring(1, s1.length() - 1).split(",");
String[] sc2 = s2.substring(1, s2.length() - 2).split("],");
StringBuilder result = new StringBuilder();
LRUCache lruCache = null;
for (int i = 0; i < sc1.length; i++) {
if (sc1[i].equals("\"LRUCache\"")){
lruCache = new LRUCache(Integer.valueOf(sc2[i].substring(1)));
result.append("null, ");
} else if (sc1[i].equals(" \"put\"")){
lruCache.put(Integer.valueOf(sc2[i].substring(2, 3)), Integer.valueOf(sc2[i].substring(5)));
result.append("null, ");
} else if (sc1[i].equals(" \"get\"")){
int val = lruCache.get(Integer.valueOf(sc2[i].substring(2)));
result.append(val + ", ");
}
}
String res = "[" + result.substring(0, result.length() - 2) + "]";
System.out.println(res);
}
}