LeetCode Problem 1704: Determine if String Halves Are Alike
You are given a string s
of even length. Split this string into two halves of the same length, and determine if these halves are “alike”. Two strings are considered alike if they have the same number of vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’). Note that the string is assumed to contain only ASCII characters.
Return true
if the two halves are alike, and false
otherwise.
Input: s = "book"
Output: true
Explanation: "bo" and "ok" both have 1 vowel so they are alike.
Input: s = "textbook"
Output: false
Explanation: "text" has 1 vowel and "book" has 2 vowels, so they are not alike.
s
, find its length n
, compute the midpoint m = n // 2
.first_half = s[:m]
, second_half = s[m:]
.vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
.True
if they are the same, otherwise False
.def halvesAreAlike(s):
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
def count_vowels(substring):
return sum(1 for char in substring if char in vowels)
n = len(s)
m = n // 2
first_half = s[:m]
second_half = s[m:]
return count_vowels(first_half) == count_vowels(second_half)
# Test cases
print(halvesAreAlike("book")) # Output: True
print(halvesAreAlike("textbook")) # Output: False
print(halvesAreAlike("AbCdEfGh")) # Output: False
print(halvesAreAlike("aA")) # Output: True
n
is the length of the string. Each character is checked exactly once, so it runs in linear time.Thus, the overall time complexity of this function is O(n).
By following this strategy, we ensure that the two halves of the given string s
are validated with respect to their vowel content efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?