Leetcode 3664. Two-Letter Card Game
- Leetcode 3664. Two-Letter Card Game
- 1. 解题思路
- 2. 代码实现
- 题目链接:3664. Two-Letter Card Game
1. 解题思路
这一题思路上挺直观的,不过翻译到代码上面就啰嗦的很,感觉今天写代码状态不太好……
整体上构造思路的话,我们不妨假设目标字符为a
,那么我们要做的就是首先找出以下三种类型的字符:
ax
xa
aa
然后分别对前两者的所有类型的字符进行统计,这里会有两种情况:
- 如果存在某一种字符串,比如
ab
,占比超过所有ax
类型字符的一半以上,那么他们无法完全内部消化,此时我们需要使用aa
类型的字符对其进行弥补;
然后,当所有多余的ax
字符以及xa
字符都被弥补之后(或者aa
字符被完全消耗之后),我们就需要考察剩下的ax
字符与xa
字符一共能匹配多少个。
此时我们分别使用贪婪算法优先计算ax
然后xa
以及反向优先xa
然后ax
两种情况,取其最大值即可。
2. 代码实现
给出python代码实现如下:
class Solution:def score(self, cards: List[str], x: str) -> int:cnt = Counter(cards)st = [it for it in cnt.items() if it[0][0] == x and it[0] != x+x]st = sorted(st, key=lambda x: x[1])st_tot = sum(it[1] for it in st)ed = [it for it in cnt.items() if it[0][1] == x and it[0] != x+x]ed = sorted(ed, key=lambda x: x[1])ed_tot = sum(it[1] for it in ed)bo = cnt[x+x]ans = 0if len(st) > 0 and st[-1][1] > st_tot // 2:ex = min(bo, st[-1][1]*2 - st_tot)st[-1] = (st[-1][0], st[-1][1]-ex)elif len(st) > 0 and st_tot % 2 == 1:ex = min(bo, 1)st[-1] = (st[-1][0], st[-1][1]-ex)else:ex = 0ans += exbo -= exst_tot -= exif len(ed) > 0 and ed[-1][1] > ed_tot // 2:ex = min(bo, ed[-1][1]*2 - ed_tot)ed[-1] = (ed[-1][0], ed[-1][1]-ex)elif len(ed) > 0 and ed_tot % 2 == 1:ex = min(bo, 1)ed[-1] = (ed[-1][0], ed[-1][1]-ex)else:ex = 0ans += exbo -= exed_tot -= exdef count(arr, bo):if len(arr) == 0:return 0, boarr = sorted(arr, key=lambda x: x[1])tot = sum(it[1] for it in arr)if tot // 2 >= arr[-1][1]:ans = tot // 2delta = 0if bo > 0 and tot % 2 == 1:delta = 1bo -= deltaelse:ans = tot - arr[-1][1]delta = arr[-1][1] - ansdelta = min(delta, bo)bo -= deltaif bo > 0 and bo <= 2 * ans:ns = (2*ans + bo) // 2bo = bo - (ns-ans)*2ans = nsans += deltareturn ans, bodef fn(arr1, arr2, bo):s1, bo = count(arr1, bo)s2, bo = count(arr2, bo)return s1 + s2return ans + max(fn(st, ed, bo), fn(ed, st, bo))
提交代码评测得到:耗时68ms,占用内存36.24MB。