Skip to content

1704. Determine if String Halves Are Alike 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  bool halvesAreAlike(string s) {
    const string a = s.substr(0, s.length() / 2);
    const string b = s.substr(s.length() / 2);
    const int aVowelsCount =
        ranges::count_if(a, [this](char c) { return isVowel(c); });
    const int bVowelsCount =
        ranges::count_if(b, [this](char c) { return isVowel(c); });
    return aVowelsCount == bVowelsCount;
  }

 private:
  bool isVowel(char c) {
    static constexpr string_view kVowels = "aeiouAEIOU";
    return kVowels.find(c) != string_view::npos;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public boolean halvesAreAlike(String s) {
    final String a = s.substring(0, s.length() / 2);
    final String b = s.substring(s.length() / 2);
    final int aVowelsCount = (int) a.chars().filter(c -> isVowel((char) c)).count();
    final int bVowelsCount = (int) b.chars().filter(c -> isVowel((char) c)).count();
    return aVowelsCount == bVowelsCount;
  }

  private boolean isVowel(char c) {
    return "aeiouAEIOU".indexOf(c) != -1;
  }
}
1
2
3
4
5
6
class Solution:
  def halvesAreAlike(self, s: str) -> bool:
    kVowels = 'aeiouAEIOU'
    aVowelsCount = sum(c in kVowels for c in s[:len(s) // 2])
    bVowelsCount = sum(c in kVowels for c in s[len(s) // 2:])
    return aVowelsCount == bVowelsCount