Sponsored
Sponsored
This method involves using two pointers to count the number of vowels in each half of the string.
By using a set to identify vowels, iterate through each character in both halves. Compare the final counts for equality to determine if they are alike.
Time Complexity: O(n), where n is the length of the string, as we iterate through the string once.
Space Complexity: O(1), since we use only a fixed amount of extra space.
1def halvesAreAlike(s: str) -> bool:
2 vowels = set('aeiouAEIOU')
3 n = len(s) // 2
4 count1 = sum(1 for i in range(n) if s[i] in vowels)
5 count2 = sum(1 for i in range(n, len(s)) if s[i] in vowels)
6 return count1 == count2
In this Python solution, a set is used to easily check if a character is a vowel. The string is split into two halves, and a generator expression counts the vowels in each half. If the counts are equal, the function returns true
.
This approach directly counts vowels in both halves of the string through string slicing.
Both halves of the string are iterated efficiently with a loop, accumulating vowel counts independently. The results are directly compared to ensure both halves are alike.
Time Complexity: O(n) - single pass counts vowels for two halves.
Space Complexity: O(1) - constant time storage allocation.
using System.Collections.Generic;
public class Solution {
public bool HalvesAreAlike(string s) {
HashSet<char> vowels = new HashSet<char> {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
int n = s.Length / 2;
int[] vowelCounts = new int[2];
for (int i = 0; i < n; i++) {
if (vowels.Contains(s[i])) vowelCounts[0]++;
if (vowels.Contains(s[i + n])) vowelCounts[1]++;
}
return vowelCounts[0] == vowelCounts[1];
}
}
In C#, synchronized object control fostered by depth-consolidate review, ensures stabilization over limited situational comparison. Leveraging HashSet iteration, localized examination of both halves achieves parity validation.