[Leet Code] Determine if String Halves Are Alike
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 (
'U'). Notice that
s contains uppercase and lowercase letters.
b are alike. Otherwise, return
Input: s = "book"
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
Input: s = "textbook"
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
Input: s = "MerryChristmas"
Input: s = "AbCdEfGh"
def halvesAreAlike(self, s):
:type s: str
vowels = ["a","e", "i", "o", "u"]
first_half = 0
answer = 0
for i in range(len(s)):
if i == len(s) / 2:
first_half = answer
answer = 0
if s[i].lower() in vowels:
answer += 1
return first_half == answer
Firstly, we define a list of all the vowels in their lowercase form. Then we define two integer variables, first_half and answer.
Then we iterate over the range of the length of the string. Then we check that if we get to the half way point, we turn the value of answer to the variable first_half. In the other if statement, we turn the string element at each position (i) to lowercase and if it’s present in the vowel list, we increment the answer variable. That then means, once we get to half of the list, and first_half variable gets its assigned value from answer, and then answer is turned to value 0, the second half of the array’s vowel number will be represented by the answer variable. Then we can check first_half == answer, it will give us a true reading if they’re equal and a false value if they’re not equal.