LeetCode 题解工作台

判断字符串的两半是否相似

给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b 。 两个字符串 相似 的前提是它们都含有相同数目的元音( 'a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U' )。注意, s 可能同时含有大写和小写…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · string·结合·计数

bolt

答案摘要

遍历字符串,若字符串前半段的元音个数等于后半段的元音个数,则返回 `true`,否则返回 `false`。 时间复杂度 ,其中 为字符串的长度。空间复杂度 ,其中 为元音字母的个数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 string·结合·计数 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个偶数长度的字符串 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 <= 1000
  • s.length 是偶数
  • s大写和小写 字母组成
lightbulb

解题思路

方法一:计数

遍历字符串,若字符串前半段的元音个数等于后半段的元音个数,则返回 true,否则返回 false

时间复杂度 O(n)O(n),其中 nn 为字符串的长度。空间复杂度 O(C)O(C),其中 CC 为元音字母的个数。

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

判断字符串的两半是否相似题解:string·结合·计数 | LeetCode #1704 简单