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.
1#include <stdbool.h>
2#include <string.h>
3
4bool isVowel(char ch) {
5 return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
6 ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
7}
8
9bool halvesAreAlike(char * s) {
10 int length = strlen(s);
11 int half = length / 2;
12 int vowelsFirstHalf = 0, vowelsSecondHalf = 0;
13 for (int i = 0; i < half; i++) {
14 if (isVowel(s[i])) vowelsFirstHalf++;
15 if (isVowel(s[i + half])) vowelsSecondHalf++;
16 }
17 return vowelsFirstHalf == vowelsSecondHalf;
18}
This C solution uses a helper function isVowel
to check if a character is a vowel. We loop through the first half of the string and the corresponding second half to count vowels and compare their counts.
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.
1using 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.