publicclassSolution{ /** * min edit cost * @param str1 string字符串 the string * @param str2 string字符串 the string * @param ic int整型 insert cost * @param dc int整型 delete cost * @param rc int整型 replace cost * @return int整型 */ publicintminEditCost(String str1, String str2, int ic, int dc, int rc){ // write code here int n = str1.length(); int m = str2.length();
// 有一个字符串为空串 if (n * m == 0) { return Math.max(n,m)*Math.min(dc,rc); }
// DP 数组 int[][] D = newint[n + 1][m + 1];
// 边界状态初始化 for (int i = 0; i < n + 1; i++) { D[i][0] = i*dc; } for (int j = 0; j < m + 1; j++) { D[0][j] = j*ic; }
// 计算所有 DP 值 for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { int left = D[i - 1][j] + dc; int down = D[i][j - 1] + ic; int left_down = D[i - 1][j - 1]; if (str1.charAt(i - 1) != str2.charAt(j - 1)) { left_down += rc; } D[i][j] = Math.min(left, Math.min(down, left_down)); } } return D[n][m]; } }
import java.util.*;
public class Solution {
/**
* lfu design
* @param operators int整型二维数组 ops
* @param k int整型 the k
* @return int整型一维数组
*/
class LFUCache{
class Node{
int k;
int val;
int freq;
public Node(){}
public Node(int k, int val, int freq){
this.k = k;
this.val = val;
this.freq = freq;
}
}
private int capacity;
private Map<Integer, Node> map = new HashMap<>();
private Map<Integer, LinkedList<Node>> freqMap = new HashMap<>();
private int minFreq;
public LFUCache(int capacity){
this.capacity = capacity;
this.minFreq = 1;
}
public void update(Node node){
LinkedList<Node> list = freqMap.get(node.freq);
list.remove(node);
if (list.isEmpty() && node.freq == minFreq){
minFreq++;
}
node.freq++;
if (!freqMap.containsKey(node.freq)){
freqMap.put(node.freq, new LinkedList<>());
}
freqMap.get(node.freq).addLast(node);
}
public int get(int k){
if (!map.containsKey(k)){
return -1;
}
Node node = map.get(k);
update(node);
return node.val;
}
public void put(int k, int val){
if (map.containsKey(k)){
Node node = map.get(k);
node.val = val;
update(node);
map.put(k, node);
return;
}
if (map.size() == capacity){
Node node = freqMap.get(minFreq).removeFirst();
map.remove(node.k);
}
Node node = new Node(k, val, 1);
map.put(k, node);
if (!freqMap.containsKey(1)){
freqMap.put(1, new LinkedList<>());
}
freqMap.get(1).addLast(node);
minFreq = 1;
}
}
public int[] LFU (int[][] operators, int k) {
// write code here
LFUCache cache = new LFUCache(k);
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < operators.length; i++){
if (operators[i][0] == 1){
cache.put(operators[i][1], operators[i][2]);
}else{
res.add(cache.get(operators[i][1]));
}
}
int[] ans = new int[res.size()];
for (int i = 0; i < ans.length; i++){
ans[i] = res.get(i);
}
return ans;
}
}