题目

You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

Example 1:

  1. Input: s = "book"
  2. Output: true
  3. Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

Example 2:

  1. Input: s = "textbook"
  2. Output: false
  3. Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
  4. Notice that the vowel o is counted twice.

Example 3:

  1. Input: s = "MerryChristmas"
  2. Output: false

Example 4:

  1. Input: s = "AbCdEfGh"
  2. Output: true

Constraints:

  • 2 <= s.length <= 1000
  • s.length is even.
  • s consists of uppercase and lowercase letters.

题意

判断一个偶数长度的字符串的前半部分和后半部分是否包含相同数量的元音字符。

思路

直接模拟统计即可。


代码实现

Java

  1. class Solution {
  2. public boolean halvesAreAlike(String s) {
  3. int count = 0;
  4. Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
  5. for (int i = 0; i < s.length() / 2; i++) {
  6. if (vowels.contains(s.charAt(i))) count++;
  7. }
  8. for (int i = s.length() / 2; i < s.length(); i++) {
  9. if (vowels.contains(s.charAt(i))) count--;
  10. }
  11. return count == 0;
  12. }
  13. }