本文最后更新于:2022年11月12日 晚上
题目描述

思路及实现
首先跟着题目走,把字符串分为长度相同的两部分part1和part2,然后再去找两部分这里边的元音数量。
为了匹配元音,可以用多种数据结构存储这个元音列表,这里我用到了集合set。
必要的东西都齐了,开始遍历就好了,如果当前字符在元音集合vowels中,那这部分的计数就加一,最后比较并返回结果即可。
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution: def halvesAreAlike(self, s: str) -> bool: vowels = set('a''e''i''o''u''A''E''I''O''U') part1 = s[:len(s) // 2] cnt1 = 0 part2 = s[len(s) // 2:] cnt2 = 0 for i in range(len(s) // 2): if part1[i] in vowels: cnt1 += 1 if part2[i] in vowels: cnt2 += 1 return True if cnt1 == cnt2 else False
|
同样的,会用Java写一写。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public boolean halvesAreAlike(String s) { Set<Character> vowels = new HashSet<Character>(); String str = "aeiouAEIOU"; int half = s.length() / 2; int cnt1 = 0, cnt2 = 0; for (int i = 0; i < str.length(); i++) { vowels.add(str.charAt(i)); } for(int i = 0; i < s.length() / 2; i++){ if (vowels.contains(s.charAt(i))){ cnt1++; } if (vowels.contains(s.charAt(half + i))){ cnt2++; } } return cnt1 == cnt2; }
|

希望本文章能够帮到您~