LeetCode每日一题11.11判断字符串的两半是否相似

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

解题思路:
1.对字符串分块
2.遍历记录每个子字符串所含元音个数
3.判断两个子字符串元音个数是否相等

代码实现:
class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        s_len = len(s)
        half_of_s = s_len // 2
        count_pre = 0.
        count_last = 0.
        for i in range(half_of_s):
            if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u' or s[i] == 'A' or s[i] == 'E' or \
                    s[i] == 'I' or s[i] == 'O' or s[i] == 'U':
                count_pre += 1
        for i in range(half_of_s, s_len):
            if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u' or s[i] == 'A' or s[i] == 'E' or \
                    s[i] == 'I' or s[i] == 'O' or s[i] == 'U':
                count_last += 1
        return count_last == count_pre


if __name__ == '__main__':
    result = Solution().halvesAreAlike(s="book")
    print(result)

你可能感兴趣的:(leetcode,算法,职场和发展)