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 <string>
2#include <unordered_set>
3
4using namespace std;
5
6bool halvesAreAlike(string s) {
7 unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
8 int half = s.size() / 2;
9 int vowelsFirstHalf = 0, vowelsSecondHalf = 0;
10 for (int i = 0; i < half; i++) {
11 if (vowels.count(s[i]))
12 vowelsFirstHalf++;
13 if (vowels.count(s[i + half]))
14 vowelsSecondHalf++;
15 }
16 return vowelsFirstHalf == vowelsSecondHalf;
17}
This C++ implementation uses an unordered set to store vowels. We compute the size of each half and count vowels in each half separately. We then compare the number of vowels in both halves to decide if they are alike.
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.
In this Java method, integer arrays are engaged to account for coinciding operations. As ongoing counts are examined within each loop iteration, synchronization is achieved using fracture-skip indexing that minimizes string traversal.