LeetCode 题解工作台
将字符串中的元音字母排序
给你一个下标从 0 开始的字符串 s ,将 s 中的元素重新 排列 得到新的字符串 t ,它满足: 所有辅音字母都在原来的位置上。更正式的,如果满足 0 的下标 i 处的 s[i] 是个辅音字母,那么 t[i] = s[i] 。 元音字母都必须以他们的 ASCII 值按 非递减 顺序排列。更正式的,…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · string·结合·排序
答案摘要
我们先将字符串中的所有元音字母存到数组或列表 中,然后我们对 进行排序。 接下来,我们遍历字符串 ,保持辅音字母不变,如果是元音字母,则依次按顺序替换为 数组中的字母。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·排序 题型思路
题目描述
给你一个下标从 0 开始的字符串 s ,将 s 中的元素重新 排列 得到新的字符串 t ,它满足:
- 所有辅音字母都在原来的位置上。更正式的,如果满足
0 <= i < s.length的下标i处的s[i]是个辅音字母,那么t[i] = s[i]。 - 元音字母都必须以他们的 ASCII 值按 非递减 顺序排列。更正式的,对于满足
0 <= i < j < s.length的下标i和j,如果s[i]和s[j]都是元音字母,那么t[i]的 ASCII 值不能大于t[j]的 ASCII 值。
请你返回结果字母串。
元音字母为 'a' ,'e' ,'i' ,'o' 和 'u' ,它们可能是小写字母也可能是大写字母,辅音字母是除了这 5 个字母以外的所有字母。
示例 1:
输入:s = "lEetcOde" 输出:"lEOtcede" 解释:'E' ,'O' 和 'e' 是 s 中的元音字母,'l' ,'t' ,'c' 和 'd' 是所有的辅音。将元音字母按照 ASCII 值排序,辅音字母留在原地。
示例 2:
输入:s = "lYmpH" 输出:"lYmpH" 解释:s 中没有元音字母(s 中都为辅音字母),所以我们返回 "lYmpH" 。
提示:
1 <= s.length <= 105s只包含英语字母表中的 大写 和 小写 字母。
解题思路
方法一:排序
我们先将字符串中的所有元音字母存到数组或列表 中,然后我们对 进行排序。
接下来,我们遍历字符串 ,保持辅音字母不变,如果是元音字母,则依次按顺序替换为 数组中的字母。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
class Solution:
def sortVowels(self, s: str) -> str:
vs = [c for c in s if c.lower() in "aeiou"]
vs.sort()
cs = list(s)
j = 0
for i, c in enumerate(cs):
if c.lower() in "aeiou":
cs[i] = vs[j]
j += 1
return "".join(cs)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) for traversing the string and sorting at most N vowels. Space complexity is O(1) extra if in-place replacement is allowed, or O(V) for storing V vowels. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check if candidate correctly identifies vowels and handles both cases.
- question_mark
Listen for discussion about maintaining consonant positions while sorting vowels.
- question_mark
Watch for explanations of ASCII-based sorting versus case-insensitive sorting.
常见陷阱
外企场景- error
Forgetting to handle uppercase vowels separately, leading to incorrect ASCII order.
- error
Modifying consonant positions while inserting sorted vowels.
- error
Assuming all strings contain vowels, causing errors when vowel list is empty.
进阶变体
外企场景- arrow_right_alt
Sort only lowercase vowels while ignoring uppercase letters.
- arrow_right_alt
Sort vowels in reverse ASCII order while keeping consonants fixed.
- arrow_right_alt
Sort vowels according to frequency of appearance instead of ASCII order.