LeetCode 题解工作台
检查字符串是否可以通过排序子字符串得到另一个字符串
给你两个字符串 s 和 t ,请你通过若干次以下操作将字符串 s 转化成字符串 t : 选择 s 中一个 非空 子字符串并将它包含的字符就地 升序 排序。 比方说,对下划线所示的子字符串进行操作可以由 "1 4234 " 得到 "1 2344 " 。 如果可以将字符串 s 变成 t ,返回 true…
3
题型
4
代码语言
3
相关题
当前训练重点
困难 · 贪心·invariant
答案摘要
题目实际上等价于判断:将字符串 中任意长度为 的子字符串采用冒泡排序交换,是否能得到 。 因此我们用一个长度为 的数组 记录字符串 中每个字符数字的下标,其中 表示数字 出现的下标列表,按从小到大排序。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你两个字符串 s 和 t ,请你通过若干次以下操作将字符串 s 转化成字符串 t :
- 选择
s中一个 非空 子字符串并将它包含的字符就地 升序 排序。
比方说,对下划线所示的子字符串进行操作可以由 "14234" 得到 "12344" 。
如果可以将字符串 s 变成 t ,返回 true 。否则,返回 false 。
一个 子字符串 定义为一个字符串中连续的若干字符。
示例 1:
输入:s = "84532", t = "34852" 输出:true 解释:你可以按以下操作将 s 转变为 t : "84532" (从下标 2 到下标 3)-> "84352" "84352" (从下标 0 到下标 2) -> "34852"
示例 2:
输入:s = "34521", t = "23415" 输出:true 解释:你可以按以下操作将 s 转变为 t : "34521" -> "23451" "23451" -> "23415"
示例 3:
输入:s = "12345", t = "12435" 输出:false
示例 4:
输入:s = "1", t = "2" 输出:false
提示:
s.length == t.length1 <= s.length <= 105s和t都只包含数字字符,即'0'到'9'。
解题思路
方法一:冒泡排序
题目实际上等价于判断:将字符串 中任意长度为 的子字符串采用冒泡排序交换,是否能得到 。
因此我们用一个长度为 的数组 记录字符串 中每个字符数字的下标,其中 表示数字 出现的下标列表,按从小到大排序。
接下来,我们遍历字符串 ,对于 中的每个字符 ,我们转为数字 ,我们判断 是否为空,若是,说明字符串 中不存在 中的数字,直接返回 false。否则,若要将 的第一个位置下标的字符交换到下标 的位置,需要满足小于 的所有数字的下标均不小于 的第一个位置下标,若不满足,返回 false。否则,我们将 的第一个位置下标弹出,然后继续遍历字符串 。
遍历结束,返回 true。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度,而 是数字集的大小,本题中 。
class Solution:
def isTransformable(self, s: str, t: str) -> bool:
pos = defaultdict(deque)
for i, c in enumerate(s):
pos[int(c)].append(i)
for c in t:
x = int(c)
if not pos[x] or any(pos[i] and pos[i][0] < pos[x][0] for i in range(x)):
return False
pos[x].popleft()
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluate how well the candidate handles greedy choices and substring sorting interactions.
- question_mark
Look for how the candidate ensures all character movements are valid and whether they recognize the invariant requirement.
- question_mark
Assess if the candidate considers the problem's edge cases and whether their solution handles large input sizes efficiently.
常见陷阱
外企场景- error
Not correctly handling the order of digits when applying substring sorts.
- error
Missing edge cases where a digit may not be movable to its correct position.
- error
Overcomplicating the solution without leveraging efficient greedy techniques or invariant checks.
进阶变体
外企场景- arrow_right_alt
Consider variants where the input string contains characters other than digits, such as lowercase letters.
- arrow_right_alt
What if the allowed operations include other kinds of substring transformations beyond sorting?
- arrow_right_alt
Explore a variant where you are given a partial target string t, and must determine the smallest substring sorts needed to complete it.