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.
1import java.util.Set;
2
3public class Solution {
4 public boolean halvesAreAlike(String s) {
5 Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
6 int n = s.length() / 2;
7 int count1 = 0, count2 = 0;
8 for (int i = 0; i < n; i++) {
9 if (vowels.contains(s.charAt(i))) count1++;
10 if (vowels.contains(s.charAt(i + n))) count2++;
11 }
12 return count1 == count2;
13 }
14}
This Java solution utilizes a set for vowel checking and then uses an integer counter to keep track of the number of vowels in each half of the string. By comparing these counts, it determines if the halves 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.