zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

2023-04-18 12:37:10 时间

题目

给你一个偶数长度的字符串 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 个。
示例 3:

输入:s = "MerryChristmas"
输出:false
示例 4:

输入:s = "AbCdEfGh"
输出:true

提示:

2 <= s.length <= 1000 s.length 是偶数 s 由 大写和小写 字母组成

解题思路

class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        leftStr, rightStr = s[:len(s)//2], s[len(s)//2:]
        from collections import Counter
        leftCount = Counter(leftStr)
        rightCount = Counter(rightStr)
        testDict = {
            'a':0,
            'e':0,
            'i':0,
            'o':0,
            'u':0,
            'A': 0,
            'E': 0,
            'I': 0,
            'O': 0,
            'U': 0,
        }
        # 找出字典的交集,得出元音字典,并导出数量
        leftDictList = leftCount.keys() & testDict.keys()
        leftDict = dict()
        for i in leftDictList:
            leftDict[i] = leftCount[i]
        # print(leftDict)

        rightDictList = rightCount.keys() & testDict.keys()
        rightDict = dict()
        for i in rightDictList:
            rightDict[i] = rightCount[i]
        # print(rightDict)
        return sum(leftDict.values()) == sum(rightDict.values())

if __name__ == '__main__':
    s = "textbook"
    s = "book"
    s = "AbCdEfGh"
    ret = Solution().halvesAreAlike(s)
    print(ret)