Leetcode刷题 2021.02.27
Leetcode1600 皇位继承顺序
一个王国里住着国王、他的孩子们、他的孙子们等等。每一个时间点,这个家庭里有人出生也有人死亡。
这个王国有一个明确规定的皇位继承顺序,第一继承人总是国王自己。我们定义递归函数 Successor(x, curOrder) ,给定一个人 x 和当前的继承顺序,该函数返回 x 的下一继承人。
马上要开学了才开始努力。这几天又要背八股文,论文不知道什么时候就要盲审,早上看了一眼一直不熟悉的dp,感觉时间真的来不及啊。还是之前玩心太重了,总之现在要充分利用好时间了。
这种设计的题目其实做的也挺少的,一开始这题想复杂了。后来借鉴了一下题解的代码,用一个map表示父子关系就行了。
class ThroneInheritance {
//map表示父子关系
Map<String, List<String>> map;
//set标记是否死亡
Set<String> isDead;
//king表示root
String king;
public ThroneInheritance(String kingName) {
map = new HashMap<>();
isDead = new HashSet<>();
king = kingName;
}
public void birth(String parentName, String childName) {
//如果有parent,就直接加到parent的map里面
if (map.containsKey(parentName)){
map.get(parentName).add(childName);
}else{
//否则新建一个parent
map.put(parentName, new ArrayList<String>());
map.get(parentName).add(childName);
}
}
public void death(String name) {
isDead.add(name);
}
public List<String> getInheritanceOrder() {
//这里从king开始递归获取字符串,因为字符串最多只调用10次,所以也不需要在过程中维护了。
List<String> res = new ArrayList<>();
if (!isDead.contains(king)) res.add(king);
dfs(king, res);
return res;
}
private void dfs(String name, List<String> res){
if (!map.containsKey(name)){
return;
}
for(String child : map.get(name)){
if (!isDead.contains(child)) res.add(child);
dfs(child, res);
}
}
}
Leetcode395 至少有 K 个重复字符的最长子串
给你一个字符串 s 和一个整数 k ,请你找出 s 中的最长子串, 要求该子串中的每一字符出现次数都不少于 k 。返回这一子串的长度。
知道是滑动窗口,但是错误提交了好多次。看了题解,发现还是比较巧妙的,做26次含有i个字符至少有k个,这样就能包含所有的情况了。
class Solution {
public int longestSubstring(String s, int k) {
char[] arr = s.toCharArray();
int res = 0;
for(int i = 1; i <= 26; i++){
res = Math.max(res, helper(arr, k, i));
}
return res;
}
private int helper(char[] arr, int k, int target){
int[] map = new int[26];
int i = 0, j = 0, n = arr.length, count1 = 0, count2 = 0, res = 0;
while (j < n){
if (map[arr[j] - 'a'] == 0) count1++;
map[arr[j] - 'a']++;
if (map[arr[j] - 'a'] == k) count2++;
while (count1 > target){
if (map[arr[i] - 'a'] == k) count2--;
map[arr[i] - 'a']--;
if (map[arr[i] - 'a'] == 0) count1--;
i++;
}
if (count1 == count2){
res = Math.max(res, j - i + 1);
}
j++;
}
return res;
}
}
Leetcode354 俄罗斯套娃信封问题
给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
这几天看dp,临时抱下佛脚吧。这题和最长上升子序列是一样的思想,但是要先排下序。首先是按照一个维度排,如果一个维度相同要按另一个维度降序排列。因为比如(1, 4), (1, 5)这种情况下,是不能组成套娃的,但是还是会进行计算。但是按降序排列的话,就会找到小于第一个维度的值了。
class Solution {
public int maxEnvelopes(int[][] envelopes) {
Arrays.sort(envelopes, (x, y) -> (x[0] == y[0] ? y[1] - x[1]: x[0] - y[0]));
int n = envelopes.length, res = 0;
int[] dp = new int[n];
for(int i = 0; i < n; i++){
dp[i] = 1;
for(int j = 0; j < i; j++){
if (envelopes[i][1] > envelopes[j][1]){
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
res = Math.max(res, dp[i]);
}
return res;
}
}