黄石商城网站建设/南宁seo推广服务
字典序
- 321. 拼接最大数
- ★316. 去除重复字母
- 386. 字典序排数
- 方法一:DFS
- 方法二:迭代
- 402. 移掉 K 位数字
- 方法:单调栈
- 1081. 不同字符的最小子序列 (同 316)
321. 拼接最大数
Leetcode
class Solution:def maxNumber(self, nums1, nums2, k):def pick_max(nums, k):stack = []drop = len(nums) - kfor num in nums:while drop and stack and stack[-1] < num:stack.pop()drop -= 1stack.append(num)return stack[:k]def merge(A, B):ans = []while A or B:bigger = A if A > B else Bans.append(bigger[0])bigger.pop(0)return ansreturn max(merge(pick_max(nums1, i), pick_max(nums2, k-i)) for i in range(k+1) if i <= len(nums1) and k-i <= len(nums2))
★316. 去除重复字母
Leetcode
class Solution:def removeDuplicateLetters(self, s: str) -> str:q, seen, count = [], set(), Counter(s)for ch in s:if ch not in seen:while q and q[-1] > ch and count[q[-1]]:# 后面还有该数并且比较大,删除。并从 seen 移除seen.remove(q.pop()) # discardq.append(ch)seen.add(ch)count[ch] -= 1return ''.join(q)
386. 字典序排数
Leetcode
方法一:DFS
class Solution:def lexicalOrder(self, n: int) -> List[int]:def dfs(cur):if cur > n: returnres.append(cur)for i in range(10): # 0-9dfs(cur * 10 + i)res = []for i in range(1, 10): # 1-9dfs(i)return res
方法二:迭代
class Solution:def lexicalOrder(self, n: int) -> List[int]:res, num = [], 1while len(res) < n:while num <= n: # 不断进入下一层res.append(num)num *= 10while num % 10 == 9 or num > n: # 不断返回上一层 ## 199 num //= 10num += 1 # 遍历该层下一个数return resclass Solution:def lexicalOrder(self, n: int) -> List[int]:return sorted(range(1, n + 1), key=str)
402. 移掉 K 位数字
Leetcode
方法:单调栈
class Solution(object):def removeKdigits(self, num, k):stack = []remain = len(num) - kfor digit in num:while k and stack and stack[-1] > digit:stack.pop() # 删除前面大的数k -= 1stack.append(digit)return ''.join(stack[:remain]).lstrip('0') or '0'
1081. 不同字符的最小子序列 (同 316)
Leetcode
2、 440. 字典序的第K小数字
3、 629. K个逆序对数组
4、 676. 实现一个魔法字典
5、 944. 删列造序
6、 955. 删列造序 II
7、 960. 删列造序 III
8、 1061. 按字典序排列最小的等效字符串
9、 1114. 按序打印
10、 1163. 按字典序排在最后的子串
11、 1415. 长度为 n 的开心字符串中字典序第 k 小的字符串
12、 1625. 执行操作后字典序最小的字符串
13、 1641. 统计字典序元音字符串的数目
14、 1718. 构建字典序最大的可行序列
15、 1754. 构造字典序最大的合并字符串