LeetCode 题解工作台
判断字符串的两半是否相似
给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b 。 两个字符串 相似 的前提是它们都含有相同数目的元音( 'a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U' )。注意, s 可能同时含有大写和小写…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · string·结合·计数
答案摘要
遍历字符串,若字符串前半段的元音个数等于后半段的元音个数,则返回 `true`,否则返回 `false`。 时间复杂度 ,其中 为字符串的长度。空间复杂度 ,其中 为元音字母的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·计数 题型思路
题目描述
给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b 。
两个字符串 相似 的前提是它们都含有相同数目的元音('a','e','i','o','u','A','E','I','O','U')。注意,s 可能同时含有大写和小写字母。
如果 a 和 b 相似,返回 true ;否则,返回 false 。
示例 1:
输入:s = "book" 输出:true 解释:a = "bo" 且 b = "ok" 。a 中有 1 个元音,b 也有 1 个元音。所以,a 和 b 相似。
示例 2:
输入:s = "textbook" 输出:false 解释:a = "text" 且 b = "book" 。a 中有 1 个元音,b 中有 2 个元音。因此,a 和 b 不相似。 注意,元音 o 在 b 中出现两次,记为 2 个。
提示:
2 <= s.length <= 1000s.length是偶数s由 大写和小写 字母组成
解题思路
方法一:计数
遍历字符串,若字符串前半段的元音个数等于后半段的元音个数,则返回 true,否则返回 false。
时间复杂度 ,其中 为字符串的长度。空间复杂度 ,其中 为元音字母的个数。
class Solution:
def halvesAreAlike(self, s: str) -> bool:
cnt, n = 0, len(s) >> 1
vowels = set('aeiouAEIOU')
for i in range(n):
cnt += s[i] in vowels
cnt -= s[i + n] in vowels
return cnt == 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) where n is the length of the string since each half is scanned once. Space complexity is O(1) extra space aside from input since only counters are maintained. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate correctly splits the string into two halves without index errors.
- question_mark
The candidate efficiently counts vowels considering case sensitivity.
- question_mark
The candidate avoids extra data structures and keeps space usage minimal.
常见陷阱
外企场景- error
Forgetting to include uppercase vowels in the count.
- error
Incorrectly dividing the string when the length is even.
- error
Returning true or false based on the halves themselves instead of their vowel counts.
进阶变体
外企场景- arrow_right_alt
Check if string quarters are alike based on vowel counts in a similar pattern.
- arrow_right_alt
Determine if halves are alike considering consonant counts instead of vowels.
- arrow_right_alt
Handle strings with non-alphabetic characters and still count only vowels for comparison.